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.
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 have a 2D Array of mostly consecutive integers. I want to take a user's integer input and locate the index of the integer one less than the user's input.
I have manually declared the first two columns in my array, and the remaining twelve columns are randomly assigned integers from a different array.
public static int[][] board = new int[4][14];
public static int[][] deal(int[] cards) {
board[0][0] = 1;
board[0][1] = 0;
board[1][0] = 14;
board[1][1] =0;
board[2][0] = 27;
board[2][1] = 0;
board[3][0] = 40;
board[3][1] = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 12; j++) {
board[i][j + 2] = cards[j + (i * 12)];
}
} return board;
}
I am trying to locate the integer one smaller than the users input and if the following integer (in the same row) is a 0, swap the 0 and the user's input.
I realize there is not a built in function indexOf for an array the following code will not run.
public static int[][] move(int[][] board) {
int input;
int place =0;
if(board.indexOf(input-1) +1 == 0){
place =board.indexOf(input);
board.indexOf(input) = 0;
board.indexOf(input-1) +1 = place;
}
return board;
}
If you really want to use the index of function, you need to switch into List(i.e. ArrayList, Vector etc) of lists . Then you code will be like this
public static ArrayList<ArrayList<Integer>> deal(int[] cards) {
ArrayList<ArrayList<Integer>> board = new ArrayList<ArrayList<Integer>>();
for(int i = 0; i < 4; i++) {
board.add(new ArrayList<Integer>);
}
board.get(0).add(1);
board.get(0).add(0);
board.get(1).add(14);
board.get(1).add(0);
board.get(2).add(27);
board.get(2).add(0);
board.get(3).add(40);
board.get(3).add(0);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 12; j++) {
board.get(i).add(cards[j + (i * 12)]);
}
}
return board;
}
Another thing you can do(and which is better because Lists have their overhead in performance) is write your own indexOf() function like below which return an array of integers because in a 2D array index means two integers(row and col):
int[] indexOf(int [] [] ar, int row, int col, int x) { //this function will find x in 2D array ar(with dimension of row*col) and return the index
int [] index = new int [2];
index [0] = index[1] = -1;
for(int i = 0; i<row; i++) {
for(int j = 0; j<col; j++) {
if(ar[i][j] == x) {
index[0] = i;
index[1] = j;
return index;
}
}
}
return index;
}
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("");
}
}
}
i need help in getting the array length from another class. i.e., passing the length of array from one class to another. Here is the problem.
Testmatrix.java
public class TestMatrix{
int rows;
int cols;
double data[][] = new double[4][4];
public TestMatrix() {
super();
rows=1; cols=1;
for(int i=0; i<=rows;i++)
{
for(int j=0; j<=cols;j++)
{
data[i][j] = 0.0;
}
}
}
public void print(){
for (int i = 0; i <data.length ; i++) {
for (int j = 0; j <data[0].length ; j++) {
System.out.print(data[i][j]+" ");
}
System.out.println();
}
}
Here is the main class
Main.java
public class Main {
public static void main(String[] args){
TestMatrix m1 = new TestMatrix();
m1.print();
}
}
Everything seems right in the constructor. But the problem is the print function. The size of the data should be 2. But its is taking the value of 4 declared that is initialised. Someone solve this for me. I need to get to print 2x2 matrix( with all 0's) but i'm getting 4x4 matrix( with all 0's)
Thanks in advance **
When you create an array, you set the size, for example new double[4][4] then that's already the size of this array, even tho you didn't insert anything in there. My point is that no matter if you insert 1 element, 2 elements, or 8 elements, that doesn't matter, inserting to array doesn't change it's size (property returned by length). Imagine a bag, you have a bag with a certain size, doesn't matter if you put items in there, size of a bag is gonna stay the same.
You declared your array as a 4x4 matrix. Line 4 should be double data[][] = new double[2][2]; in order to achieve what you seem to want.
Initializing array doesn't change the size of an array. If you want to print acording to new row and column size, change your print() method to:
public void print() {
for (int i = 0; i <= rows ; i++) {
for (int j = 0; j <= cols ; j++) {
System.out.print(data[i][j]);
}
System.out.println();
}
}
Again, constructor name should be same as class name. But the constructor of TestMatrix is Matrix.
Note: Another important thing, you don't need to initialize the double array to 0.0. This array is by default initialized to 0.0 as this is an instance field of the class. According to Oracle:
Each class variable, instance variable, or array component is
initialized with a default value when it is created.
For type double, the default value is positive zero, that is, 0.0d.
Also, change your TestMatrix(int rows, int cols, double[] data) constructor to:
// declare with a large size
double data[][] = new double[80][80];
public TestMatrix(int rows, int cols, double[] data) {
super();
this.rows = rows;
this.cols = cols;
for (int i = 0, k = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
this.data[i][j] = data[k++];
}
}
}
Better practice would be making the fields private and write getter and setter methods for those fields.
Either declare matrix to 2*2 as said by Chris
or change
for (int i = 0; i < data.length ; i++) {
for (int j = 0; j < data.length ; j++) {
to
for (int i = 0; i <= rows ; i++) {
for (int j = 0; j <= cols ; j++) {
If you want any size of matrix upto 4*4 use second solution.
You probably want something like this;
public class Matrix {
public final double[][] values;
public final int rows;
public final int cols;
public Matrix(int rows, int cols) {
this.rows = rows;
this.cols = cols;
values = new double[rows][cols]; // Automatically 0.0.
}
public void print() {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
System.out.printf(" %6f", values[i][j]);
}
System.out.println();
}
}
}
Matrix m = new Matrix(2, 2);
...
rows and cols are redundant, as you already used values.length, and values[0].length.
A few notes:
Use an IDE, your code did not even compile, this is the minimum
effort you should put into any problem.
Declaring the array as double data[][] = new double[4][4]; makes an array that is 4 "boxes" wide and 4 "boxes" tall. each box will hold a data of the type specified, in your case a double which you are setting to 0.0
public class TestMatrix
{
int rows;
int cols;
double data[][] = new double[2][2];
public TestMatrix()
{
rows = 1;
cols = 1;
for (int i = 0; i <= rows; i++)
{
for (int j = 0; j <= cols; j++)
{
data[i][j] = 0.0;
}
}
}
public void print()
{
for (int i = 0; i < data.length; i++)
{
for (int j = 0; j < data[0].length; j++)
{
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args)
{
TestMatrix m1 = new TestMatrix();
m1.print();
}
}
In Addition to above answers
i'm getting 4x4 matrix( with all 0's)
If you wanna find difference replace the existing lines with below code
data[i][j] = 1.0;
System.out.print(data[i][j]+" ");
Hope you understand the reason for getting all the 0's
Your class should be like this:
public class Test {
int rows;
int cols;
double data[][] = new double[2][2];
public void print() {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data.length; j++) {
System.out.print(" "+data[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
Test m1 = new Test();
m1.print();
}
}
and this part you can delete. You do not need it. This is not an initialization.
public void matrix() {
rows = 1;
cols = 1;
for (int i = 0; i <= rows; i++) {
for (int j = 0; j <= cols; j++) {
data[i][j] = 0.0;
}
}
}
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;
}