I want to swap Columns and Rows in a 2D array.
My problem is that I want the Variable "oldField" to save the oldField. The Variable I think is Pointing on the same Object as newField and so it get´s changed even tho I dont want that.
Id like to know how I can save the Variable oldField independent
public int[][] swapMatrix(int[][] pField) { // swaps the rows and columns in
// a Field
int[][] oldField = pField.clone();
int[][] newField = pField.clone();
for (int i = 0; i < newField.length; i++) {
for (int j = (newField.length - 1); j >= 0; j--) {
newField[i][(newField.length - 1) - j] = oldField[j][i];
}
}
return newField;
}
When you copy in 1-D array with primitive value like int then the new array and content copy to it and there is no reference.
int row1[] = {0,1,2,3};
int row2[] = row1.clone();
row2[0] = 10;
System.out.println(row1[0] == row2[0]); // prints false
but for 2-D array the content is object and clone method only do shallow copy not create new content if object is there .For your requirement you need to do deep copy.
int table1[][]={{0,1,2,3},{11,12,13,14}};
int table2[][] = table1.clone();
table2[0][0] = 100;
System.out.println(table1[0][0] == table2[0][0]); //prints true
this code solves your problem:
public class SwapRowsAndColumns {
public static void main(String[] args) {
int[][] someMatrix = new int[2][3];
someMatrix[0][0] = 1;
someMatrix[0][1] = 2;
someMatrix[0][2] = 3;
someMatrix[1][0] = 4;
someMatrix[1][1] = 5;
someMatrix[1][2] = 6;
printMatrix(someMatrix);
int[][] invertedMatrix = swapMatrix(someMatrix);
printMatrix(invertedMatrix);
}
private static int[][] swapMatrix(int[][] pField) {
int originalTotalRows = pField.length;
int originalTotalColumns = pField[0].length;
int[][] newMatrix = new int[originalTotalColumns][originalTotalRows];
for(int i=0; i< originalTotalRows; i++){
for(int j=0; j < originalTotalColumns; j++){
newMatrix[j][i] = pField[i][j];
}
}
return newMatrix;
}
private static void printMatrix(int[][] matrix){
int totalRows = matrix.length;
int totalColumns = matrix[0].length;
for(int i=0; i< totalRows; i++){
for(int j=0; j< totalColumns; j++){
System.out.print(matrix[i][j] + " ");
}
System.out.println("");
}
}
}
Related
I have to define a method called getDistance. That takes the following string:
0,900,1500<>900,0,1250<>1500,1250,0 and returns a 2d array with the all the distances. The distances are separated by "<>" symbol and they are separated into each column by ",".
I know I need to use String.split method. I know splitting by the commmas will give me the columns and splitting it by the "<>" will give me the rows.
public static int[][] getDistance(String array) {
String[]row= array.split(",");
String[][] distance;
int[][] ctyCoord = new int[3][3];
for (int k = 0; k < row.length; k++) {
distance[k][]=row[k].split("<>");
ctyCoord[k][j] = Integer.parseInt(str[j]);
}
return ctyCoord;
This is a working dynamic solution:
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] _2d = null;
// let us take the column size now, because we already got the row size
if (rows.length > 0) {
String[] cols = rows[0].split(",");
_2d = new int[rows.length][cols.length];
}
for (int i = 0; i < rows.length; i++) {
String[] cols = rows[i].split(",");
for (int j = 0; j < cols.length; j++) {
_2d[i][j] = Integer.parseInt(cols[j]);
}
}
return _2d;
}
Let's test it:
public static void main(String[] args) {
String given = "0,900,1500<>900,0,1250<>1500,1250,0";
int[][] ok = getDistance(given);
for (int i = 0; i < ok.length; i++) {
for (int j = 0; j < ok[0].length; j++) {
int k = ok[i][j];
System.out.print(k + " ");
}
System.out.println();
}
}
I think you should first split along the rows and then the colums. I would also scale the outer array with the number of distances.
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] out = new int[rows.length][3];
for (int i = 0; i < rows.length, i++) {
String values = rows[i].split(",");
for (int j = 0; j < 3, j++) {
out[i][j] = Integer.valueOf(values[j]);
}
}
return out;
I need to create a method within my class to add two 2d arrays together. One is implemented as a parameter in the method, while the other is a class object. I need to make sure the arrays are the same size, and if so, add them together. I keep getting an Array Out of Bounds error. Whats wrong with my code?
// method to add matrices
public int[][] add(int[][] matrix) {
int addedMatrices[][] = new int[row][column];
if (userArray[row][column] == matrix[row][column]) {
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
System.out.println(addedMatrices[i][j]);
}
}
}
return addedMatrices;
}
if (userArray[row][column] == matrix[row][column]) is the problem.
Remember that arrays are zero-indexed so the elements are numbered from zero to row - 1. Trying to access row row is guaranteed to throw an ArrayIndexOutOfBoundsException because the last row is at index row - 1.
I'm not sure why you even have this line. If you change row to row - 1 and column to column - 1 then this line checks if the bottom-right values in the two matrices are the same. If they're not then the matrices will not be summed. Is that what you intended to do?
I think this is what you are trying to do :
public class Test {
static int row =3;
static int column =2;
static int[][] userArray = new int[][] {{1,1},{2,2},{3,3}};
public static void main(String[] args) {
add(new int[][] {{4,4},{5,5},{6,6}});
}
// method to add matrices
public static int[][] add(int[][] matrix) {
int addedMatrices[][] = new int[row][column];
//check arrays are of the same size
if ((userArray.length == matrix.length) && (userArray[0].length == matrix[0].length) ) {
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
//printout
if(j == (column -1)) {
for(int col = 0; col < column; col++) {
System.out.print(addedMatrices[i][col]+ " ");
}
}
System.out.println();
}
}
}
return addedMatrices;
}
}
or better:
public class Test {
static int[][] userArray = new int[][] {{1,1},{2,2},{3,3}, {4,4}};
public static void main(String[] args) {
add(new int[][] {{5,5},{6,6},{7,7},{8,8}});
}
// method to add matrices
public static int[][] add(int[][] matrix) {
//check arrays are of the same size
if ((userArray.length != matrix.length) || (userArray[0].length != matrix[0].length) ) {
System.out.println("Error: arrays are not of the same size");
return null;
}
int rows = userArray.length;
int cols = userArray[0].length;
int addedMatrices[][] = new int[rows][cols];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
//printout
if(j == (cols -1)) {
for(int col = 0; col < cols; col++) {
System.out.print(addedMatrices[i][col]+ " ");
}
}
System.out.println();
}
}
return addedMatrices;
}
}
to make the print out more elegant you could change the for loop to :
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
}
System.out.println(Arrays.toString(addedMatrices[i]));
}
The line if (userArray[row][column] == matrix[row][column]) { should be replaced by a line to check if the dimensions of both matrices are the same (I guess that is what's intended). Assuming they are both rectangular arrays, and non empty:
public class MatrixAdder {
static public int[][] userArray = {{1,2},{3,4},{5,6}};
static public int[][] add(int[][] matrix) {
final int nb_rows1 = matrix.length; // nb rows in matrix
final int nb_cols1 = matrix[0].length; // nb columns in matrix
final int nb_rows2 = userArray.length; // nb rows in userArray
final int nb_cols2 = userArray[0].length; // nb columns in userArray
// this assumes A[0] exists, and A[0].length == A[1].length == ...
// both for matrix and userArray
int addedMatrices[][] = new int[nb_rows1][nb_rows1];
if ((nb_rows1==nb_rows2) && (nb_cols1==nb_cols2)) {
for (int i = 0; i < nb_rows1; ++i) {
for (int j = 0; j < nb_cols1; ++j) {
addedMatrices[i][j] = matrix[i][j] + userArray[i][j];
System.out.println(addedMatrices[i][j]);
}
}
}
return addedMatrices;
}
static public void main(String[] args)
{
int[][] mx1 = {{10,100},{20,200},{40,400}};
int [][] mx2 = add(mx1);
}
}
To be more robust, you could check that the dimensions of all sub-arrays are the same. You could also check if the matrix has zero dimension (otherwise array[0] will give an error).
If the dimensions are not the same, the returned matrix is filled with zeroes.
If this is not exactly what you need, it should give you enough hints.
if (userArray[row][column] == matrix[row][column]) {}
This is strange to me, I honestly don't know what the intentions are (Your just comparing the last element of each array).
I would do
if(addedMatrices.length == userArray.length && addedMatrices.length == matrix.length){}.
This is ugly but I don't know anything about userArray or matrix. I am presuming userArray is global. Also do j++ and i++, it has the same end result but it is more of the norm.
I came across this problem called compress. The objective is to take an array, remove any repeated values and return a new array.
I know this would be very easy with ArrayLists, but I want to do it without them.
So far, I've just written a loop to determine the number of unique values so I can construct a new array of the appropriate length. How can I then get the unique values into the new array?
public static int[] compress(int[] array){
int length = 0;
boolean contains = false;
for (int i = 0; i < array.length; i++){
contains = false;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
contains = true;
j = i;
} else {
contains = false;
}
}
if (!contains){
length++;
}
}
int[] uniqueArray = new int[length];
}
Not Tested but I think this should do the trick.
public static int[] copyArray(int [] num){
int x = 0;
int numDuplicate = 0;
int[] copy = new int[num.length]; // we use this to copy the non duplicates
HashMap<Integer, Integer> count = new HashMap<>(); //hashmap to check duplicates
for(int i = 0; i < num.length; i++){
if(count.containsKey(num[i])){
count.put(num[i], count.get(num[i])+1);
numDuplicate++; // keep track of duplicates
}else{
count.put(num[i], 1); // first occurence
copy[x] = num[i]; // copy unique values, empty values will be at end
x++;
}
}
// return only what is needed
int newSize = num.length - numDuplicate;
int[] copyNum = new int[newSize];
for(int i = 0; i < copyNum.length; i++){
copyNum[i] = copy[i];
}
return copyNum;
}
public static void main(String[] args) {
// sample elements
int[] nums = new int[20];
for(int i = 0; i < nums.length; i++){
nums[i] = (int)(Math.random() * 20);
}
System.out.println(Arrays.toString(nums));
System.out.println(Arrays.toString(copyArray(nums)));
}
I am trying to make a 2D array that i can dynamically update. Lets say i have a 2D array with 10 rows and 3 columns. I want to add an int value to a specific row, thereby adding an extra column to that row (and only that row) so that it alone would have 4 columns. Here's what i have so far.
public class DynamicArray {
private int[][] array;
private int size;
public DynamicArray(int initialSize) {
array = new int[10][initialSize];
size = 0;
}
public int get(int j) {
return array[0][j];
}
public int getSize() {
return size;
}
public void put(int N) {
if (size < array[0].length)
array[0][size] = N;
else // need to create a bigger array
{
int[][] temp = new int[10][2 * size];
for (int i = 0; i < array.length; i++)
for (int j = 0; j < array[i].length; j++)
temp[i][j] = array[i][j];
temp[0][size] = N;
array = temp;
}
size = size + 1;
}
public static void main(String[] args) {
DynamicArray da = new DynamicArray(3);
da.put(2);
da.put(1);
da.put(3);
da.put(1);
da.put(4);
da.put(5);
for (int i = 0; i < da.getSize(); i++) {
for (int j = 0; j < 9; j++) {
System.out.print((da.get(i) + "\t"));
}
System.out.println("\n");
}
}
}
The problem is that with this code the program adds the new value to each row instead of only the one specified (in this case row 0).
How could I fix this?
Additionally, how could i make the program do the opposite as well -> remove a value from an individual row and shorten that row?
In case you just want to add the new element to the new array[0].
public void put(int N) {
if (size < array[0].length)
array[0][size] = N;
else { // need to create a bigger array
int[] temp = new int[2 * size]; // Temporary create a new array with double size
// fill the empty array with array[0] existing elements
for (int i = 0; i < size; i++) {
temp[i] = array[0][i];
}
// Change the array[0] to point to the new array
array[0] = temp;
// Add the new element to the new array
array[0][size] = N;
}
size = size + 1;
}
In case you want to put to a specific row number and you should get that as an argument in the put method.
public void put(int N, int rowNum);
You should also change the size element to be a array which will track the size of each row.
int[] size = new int[10];
Accordingly change the size of the row only when that specific row that reached its limit.
Check the code below
public class DynamicArray {
private int[][] array;
private int[] size;
public DynamicArray(int initialSize) {
array = new int[10][initialSize];
size = new int[10];
}
public int get(int rowNum, int colNum) {
return array[rowNum][colNum];
}
public int getSize(int rowNum) {
return size[rowNum];
}
public void put(int N, int rowNum) {
if (size[rowNum] < array[0].length)
array[rowNum][size[rowNum]] = N;
else { // need to create a bigger array
int[] temp = new int[2 * size[rowNum]];
for (int i = 0; i < size[rowNum]; i++) {
temp[i] = array[rowNum][i];
}
array[0] = temp;
array[0][size[rowNum]] = N;
}
size[rowNum] = size[rowNum] + 1;
}
public static void main(String[] args) {
DynamicArray da = new DynamicArray(3);
da.put(2, 0);
da.put(1, 0);
da.put(3, 0);
da.put(1, 0);
da.put(4, 0);
da.put(5, 1);
da.put(2, 4);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < da.getSize(i); j++) {
System.out.print((da.get(i, j) + "\t"));
}
System.out.println("\n");
}
}
}
public static int[][] copyMatrix(int[][] matrix)
{
for (int i = 0; (i < matrix.length); i++)
{
int[][] duplicateMatrix = new int[matrix.length][matrix[i].length];
for (int j = 0; (j < matrix[i].length); j++)
{
duplicateMatrix[i][j] = matrix[i][j];
}
}
return duplicateMatrix;
}
hello all, this specific function doesnt seem to work since duplicateMatrix isnt initialized as a variable, but I cant seem to initialize since its being created in the loop, I cant find a way to generate the amount of cells need in a column.
help will be appreciated. thanks.
You should initialize the array before the loops, since you only want to initialize it once.
public static int[][] copyMatrix(int[][] matrix)
{
if (matrix.length < 1) {
return new int[0][0];
}
int[][] duplicateMatrix = new int[matrix.length][matrix[0].length];
for (int i = 0; (i < matrix.length); i++)
{
for (int j = 0; (j < matrix[i].length); j++)
{
duplicateMatrix[i][j] = matrix[i][j];
}
}
return duplicateMatrix;
}
This code assumes that all the rows in your input array have the same number of elements (which is true for matrices).
You can relax this assumption if you remember that a 2-dimentional array is simply an array of arrays :
public static int[][] copyMatrix(int[][] matrix)
{
int[][] duplicateMatrix = new int[matrix.length][];
for (int i = 0; (i < matrix.length); i++)
{
duplicateMatrix[i] = new int[matrix[i].length];
for (int j = 0; (j < matrix[i].length); j++)
{
duplicateMatrix[i][j] = matrix[i][j];
}
}
return duplicateMatrix;
}
A two-dimensional array is an array of arrays. You must first create the two-dimensional array, and then each one of its element individually:
public static int[][] copyMatrix(int[][] matrix)
{
int[][] duplicateMatrix = new int[matrix.length][];
for (int i = 0; (i < matrix.length); i++)
{
duplicateMatrix[i] = new int[matrix[i].length];
for (int j = 0; (j < matrix[i].length); j++)
{
duplicateMatrix[i][j] = matrix[i][j];
}
}
return duplicateMatrix;
}