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;
}
Related
[[4390, Apple, $1.59],[4046, Avocado, $0.59],null, null]
I am trying to copy the above two dimensional array with for loop, but I got:
[[4390, Apple, $1.59],[4046, Avocado, $0.59],[null, null, null],[null, null, null]
What should I do to get null instead of [null, null, null] without importing Array?
Following is my code. Assume the array I want to copy is called "marketItems"
int nullIndex = marketItems.length;
for(int j = 0; j < marketItems.length; ++j) {
if(marketItems[j] == null) {
nullIndex = j;
break;
}
}
String[][]copy = new String[marketItems.length][3];
for(int i = 0; i < nullIndex; ++i ) {
for(int j = 0; j < marketItems[i].length; ++j) {
copy[i][j] = marketItems[i][j];
}
}
for(int i = nullIndex; i < marketItems.length; ++i) {
marketItems[i] = null;
}
Well for practical code, you should be importing and using Arrays (or something) rather than implementing this by hand. But assuming that this is a learning exercise ...
The problem is this line:
String[][]copy = new String[marketItems.length][3];
This is explicitly allocating a rectangular 2-D array. But your requirement is for a ragged array where some of the first level subarrays are actually null.
This is a simpler, cleaner way of doing it:
String[][] copy = new String[marketItems.length][];
That allocates just the top-level array, with the sub-array references default initialized to null. Then you allocate sub-arrays as required for the non-null sub-arrays in the original marketItems object ... and populate them.
for (int i = 0; i < marketItems.length; i++) {
if (marketItems[i] != null) {
copy[i] = new String[marketItems[i].length];
for (int j = 0; j < marketItems[i].length; j++) {
copy[i][j] = marketItems[i][j];
}
}
}
(That is about half the number of lines of code in the original version. And it will be more efficient, and easier to understand for someone who can read Java.)
public class Test {
public static void main(String[] args) {
String[][] marketItems = new String[][]{
{"4390", "Apple"," $1.59"},{"4046", "Avocado", "$0.59"},null,null
};
int nullIndex = marketItems.length;
for(int j = 0; j < marketItems.length; ++j) {
if(marketItems[j] == null) {
nullIndex = j;
break;
}
}
String[][]copy = new String[marketItems.length][3];
for(int i = 0; i < nullIndex; ++i ) {
for(int j = 0; j < marketItems[i].length; ++j) {
copy[i][j] = marketItems[i][j];
}
}
for(int i = nullIndex; i < marketItems.length; ++i) {
// marketItems[i] = null;
copy[i]=null;
}
System.out.println(Arrays.deepToString(copy));
}
}
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;
This question already has answers here:
copy a 2d array in java
(5 answers)
Closed 4 years ago.
I know that similar questions have been asked, but after reading their answers, I keep being unable to solbe my problem: I need to implement the Java method clone, which copies all the double entries in a given two-dimensional array a to a newly created two-dimensional array of the same type and size. This method takes the array a as input and returns the new array with the copied values.
IMPORTANT: I am not not allowed to use a library method to clone the array.
Here's what I've done so far: Maybe I didn't understand the requirements but it didn't work:
class Solution {
static double[][] clone(double[][] a) {
double[][] b = new double[a.length][a.length];
for (int i = 0; i < a.length; i++) {
b[i][i] = a[i][i];
}
return b;
}
}
This is the error message I get:
Status: Done
cloneLonger(weblab.UTest) failed: 'java.lang.AssertionError: expected:<3> but was:<2>'
Test score: 2/3
Something like this should work (with library method):
public class Util{
// clone two dimensional array
public static boolean[][] twoDimensionalArrayClone(boolean[][] a) {
boolean[][] b = new boolean[a.length][];
for (int i = 0; i < a.length; i++) {
b[i] = a[i].clone();
}
return b;
}
}
In this, your code has few mistakes. These corrections were done below. The two-dimension array has 2 lengths. In this case, you didn't consider inside array length.
class Solution {
static double[][] clone(double[][] a) {
double[][] b = new double[a[0].length][a.length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
}
you should iterate this array with two loops. This will helps you:
static double[][] clone(double[][] a) {
double[][] b = new double[a.length][];
for (int i = 0; i < a.length; i++) {
b[i]= new double[a[i].length];
for (int j = 0; j < a[i].length; j++)
b[i][j] = a[i][j];
}
return b;
}
You have some logical mistakes:
1. Matrix could be sized M x N where M is the number of rows and N is the number of columns. In your solution you are taking for granted that M is always equal to N.
2. You are iterating trough all the rows and there you do set only one column per row like target[K][K] = source[K][K] -> this will go copy the diagonal only and not the whole matrix.
Copy to a temp single row array and then assign it to the out array
static double[][] clone(double[][] a) {
double[][] b = new double[a.length][];
for (int i = 0; i < a.length; i++) {
double[] temp = new double[a[i].length];
for (int j = 0; j < temp.length; j++) {
temp[j] = a[i][j];
}
b[i] = temp;
}
return b;
}
Ever more "advanced" alternatives are:
static double[][] clone(double[][] a) {
double[][] b = new double[a.length][];
for (int i = 0; i < a.length; i++) {
b[i] = new double[a[i].length];
//for (int j = 0; j < a[i].length; ++j) {
// b[i][j] = a[i][
//}
System.arraycopy(a[i], 0, b[i], a[i].length);
}
return b;
}
Now there is a utility class Arrays worth knowing:
static double[][] clone(double[][] a) {
double[][] b = new double[a.length][];
for (int i = 0; i < a.length; i++) {
b[i] = Arrays.copyOf(a[i], 0, [a[i].length]);
}
return b;
}
And for primitive arrays the clone method still may be used. Cloning is not very pure, bypassing constructors, and might be dropped from java in some future.
static double[][] clone(double[][] a) {
double[][] b = new double[a.length][];
for (int i = 0; i < a.length; i++) {
b[i] = a[i].clone();
}
return b;
}
You can't create new array like that. If you are sure that length and width of array is same than only this will work.
class Solution {
static double[][] clone(double[][] a) {
boolean[][] b = new boolean[a.length][];
for (int i = 0; i < a.length; i++) {
b[i] = new double[a[i].length];
for (int j = 0; i < a[i].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
}
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.
Hello I create a 2D array and i want to find the position from the first 2 in the array. And after to add the index in a new ArrayList. But this code doesn't work. Any idea for the problem?
import java.util.ArrayList;
class Test {
public static void main(String[] args) {
ArrayList<Integer> tableau = new ArrayList<Integer>();
int[][] tab = {
{1,1,1,1,1,1,2,1,1,2,1,1,1,2,1,2,1,1,1,1,1},
{1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1},
};
for (int i = 0; i < tab.length; i++) {
int j = tab[i].indexOf(2);
for (int k = j ; k < tab[i].length; k++) {
if (tab[i][j] == 2){
tableau.add(j);
}
}
}
for (Integer row : tableau) {
System.out.println("row = "+ Arrays.toString(tableau));
}
}
}
As others have mentioned, regular arrays do not have an indexOf method, meaning that you will get an error when you compile.
However, you can easily create your own method to use as a substitute.
private static int indexOf(int value, int[] array)
{
for (int i=0; i<array.length; i++)
{
if (array[i] == value)
return i;
}
return -1;
}
Then you can just replace this line:
int j = tab[i].indexOf(2);
With this one:
int j = indexOf(2, tab[i]);