How to add numbers inside 2D arrays - java

So I want to add the rows and columns in this 2D array right here.
The array looks like this:
int[][] array = new int[3][3];
array[0][0] = 0;
array[1][0] = 0;
array[2][0] = 0;
array[1][0] = 0;
array[1][1] = 1;
array[1][2] = 2;
array[2][0] = 0;
array[2][1] = 2;
array[2][2] = 4;
So I have this set up in a 3x3 matrix on a sheet of paper and the first row should print out 0, second row should print out 3, third row should print out 6
first column should print out 0, second column should print out 3, third column should print out 6.
I have no clue where to start and I just need to see how to do this problem, because I have a few questions after this that involve this, so if you can just give me code that I can read it would be really helpful! Thanks!

The simplest way is to create two for loops - outer one goes through the rows, inner one goes through the columns. Then sum up the values for every column of a given row.
int[] colSums = {0,0,0};
for (int c=0;c<array.length;c++) {
int rowSum = 0;
for (int c2=0;c2<array[c].length;c2++) {
rowSum += array[c][c2];
colSums[c2] += array[c][c2];
}
System.out.println("Sum of row "+c+": "+rowSum);
}
for (int c=0;c<colSums.length;c++) {
System.out.println("Sum of column "+c+": "+colSums[c]);
}

Related

Print characters as a Matrix

Below problem has a list of characters and number of columns as the input. Number of columns is not a constant and can vary with every input.
Output should have all the rows fully occupied except for the last one.
list: a b c d e f g
colums: 3
Wrong:
a b c
d e f
g
Wrong:
a d g
b e
c f
Correct:
a d f
b e g
c
I have tried below:
public static void printPatern(List<Character> list, int cols) {
for (int i = 0; i < cols; i++) {
for (int j = i; j < list.size(); j += cols) {
System.out.print(list.get(j));
}
System.out.println();
}
}
It gives output as (which is wrong):
a d g
b e
c f
I am trying to come with an algorithm to print the correct output. I want to know what are the different ways to solve this problem. Time and Space complexity doesn't matter. Also above method which I tried is wrong because it takes columns as the parameter but that's actually acting as the number of rows.
FYI: This is not a HOMEWORK problem.
Finally able to design the algorithm for this problem
Please refer below java code same
public class puzzle{
public static void main(String[] args){
String list[] = { "a", "b", "c","d","e","f","g","h","i","j" };
int column = 3;
int rows = list.length/column; //Calculate total full rows
int lastRowElement = list.length%column;//identify number of elements in last row
if(lastRowElement >0){
rows++;//add inclomplete row to total number of full filled rows
}
//Iterate over rows
for (int i = 0; i < rows; i++) {
int j=i;
int columnIndex = 1;
while(j < list.length && columnIndex <=column ){
System.out.print("\t"+list[j]);
if(columnIndex<=lastRowElement){
if(i==rows-1 && columnIndex==lastRowElement){
j=list.length; //for last row display nothing after column index reaches to number of elements in last row
}else{
j += rows; //for other rows if columnIndex is less than or equal to number of elements in last row then add j value by number of rows
}
}else {
if(lastRowElement==0){
j += rows;
}else{
j += rows-1; //for column greater than number of element in last row add j = row-1 as last row will not having the column for this column index.
}
}
columnIndex++;//Increase column Index by 1;
}
System.out.println();
}
}
}
This is probably homework; so I am not going to do it for you, but give you some hints to get going. There are two points here:
computing the correct number of rows
computing the "pattern" that you need when looping your list so that you print the expected result
For the first part, you can look into the modulo operation; and for the second part: start iterating your list "on paper" and observe how you are printing the correct result manually.
Obviously, that second part is the more complicated one. It might help if you realize that printing "column by column" is straight forward. So when we take your correct example and print the indexes instead of values, you get:
0 3 6
1 4 7
2 5
Do that repeatedly for different input; and you will soon discover the pattern of indexes that you need to print "row by row".

Filling 2d array

Okay probably it's a very easy solution, but I can't seem to find it. I've got two ArrayLists:
ArrayList<Candidate>partyList and ArrayList<Party>electoralList
Now I want to make a 2d int array that represents the parties and candidates like this:
p c
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
etc.
I think I already have the right for-loop to fill the array but I only miss the correct formula to do it.
int[][]ArrList;
for (int i=0; i<parties.size(); i++){
for(int j=0; j<parties.get(i).getPartyList().size(); j++){
ArrList[i][j]=
Is the for-loop indeed correct? And what is the formula to fill the array then?
I will try and answer the question from how I understood what you are looking for here.
You should understand this first:
A 2D array consists of a nestled array i.e. ArrList[2][3] = [ [1,2,3], [1,2,3] ] -> The first digit declares How many arrays as elements, the second digit declares Size or if you like: length, of the array elements
If you are looking for to represent the candidates and parties as numbers. Here is my solution:
int[][]ArrList = new int[parties.size()][electoral.size()]
for (int depth=0; depth < parties.size(); depth++){
for(int itemIndex=0; itemIndex<parties.get(depth).getPartyList().size(); itemIndex++){
ArrList[depth][itemIndex]= itemIndex;
I hope this is what you were looking for.
First of all, ArrList should not have a starting capital letter (it is not a class but an object).
Second point (I think what troubles you) is that you are not initializing the matrix and the parties.size() are always 0. I am not sure since there is not enough code though.
You could do something like this
int ROWS = 10;
int COLS = 2;
int [][] matrix = new int[ROWS][];
for(int i=0; i< matrix.length; i++){
matrix[i] = new int[COLS];
}
or, with lists
int ROWS = 10;
int COLS = 2;
List<List<Object>> matrix = new ArrayList<>(ROWS);
for (int i = 0; i < ROWS; i++) {
ArrayList<Object> row = new ArrayList<>(COLS);
for (int j = 0; j < COLS; j++) {
row.add(new Object());
}
matrix.add(row);
}
int[][] arrList=new int[parties.size()][2];
int i=0,j=0,k=0;
for(;i<parties.size();i++,j++){
if(j==1){
arrList[k][j]=electoralList .get(--i);
j=-1;
k++;
}
else{
arrList[k][j]=parties.get(i);
}
}
arrList[k][j]=aarM.get(electoralList .size()-1);
System.out.println(Arrays.deepToString(arrList));

2D array shift up or down for column for square matrix

I know how to shift the row of the 2d array of type double
where i is the matrix size
public static void rowshiftRight(int i, double[][] array) {
int m = array[i].length;
double temp = array[i][m-1];
for (int k=m-1; k>=1; k--){
array[i][k] = array[i][k-1];
}
array[i][0] = temp;
}
I'm trying to change the above logic to shiftcolum, any help will be grateful
//wrong code
public static void colshiftdownorup(int i, double[][] array) {
int m = array.length;
double temp = array[m-1][i];
for (int k=m-1; k>=1; k--){
array[k][i] = array[k-1][i];
}
array[i][0] = temp;
}
The error appears to be at the last line of colshiftRight
Change :
array[i][0] = temp;
to :
array[0][i] = temp;
You may also want to rename the method to colshiftDown
Basically, to shift a column you will need some extra checks since 2D arrays are not always perfect matrices, e.g.:
int[][] array = new int[4][]; might be like this
2 3 4 5
1 1 1
1 2
1 2 3 4
If you want to shift 3rd column (4,1,null,3) you will see the extra work required to control null values.

how to iterate on array[...][i] (columns) in java

There is a really easy way to access the rows of a 2D array in java
for (int i = 0 ; i < integer2D.length ; i++)
getMyArray(integer2D[i]);
But, I searched in the web to find such easy way to iterate on columns of the 2D-array, like
for (int j = 0 ; j < integer2D[0].length ; j++)
getMyArray(integer2D[][i]);
or
for (int j = 0 ; j < integer2D[0].length ; j++)
getMyArray(integer2D[...][i]);
which works in some programming languages. I just found the class RealMatrix and MatrixUtils that I can convert my array2D to a real matrix and then transpose it and again convert it to an array and iterate on it. But I suppose that there exist a simpler way?
Edit: iterating on rows as I noted in the first piece of code is easy but the main question is how to iterate on columns like the second and third codes work in some other programming languages.
Edit2: As I mentioned in the last paragraph of the main question, the easiest way that I know is transposing the matrix and the iterating on its rows.
If I understand your question, you could use a for-each as an easy way to get each row like
for (int[] row : integer2D) { // <-- for each int[] in the int[][]
for (int val : row) { // <-- for each int in the int[] row
// ...
}
}
For this, you can use the BigMatrixImpl Class of the commons math library. It has a getColumnAsDoubleArray() method which will return the specified column as an array.
Delivering only one index will give you the whole row, so:
integer2D[5] // returns an int[]
will give you an integer array, which is the 6th row in your matrix.
If you supply both indexes directly you get the value of the "cell"
integer2D[5][1] // returns an int
will give you the value of the second column of the 6th row.
This is direct access to your matrix, if you want to iterate through the rows the answer from Elliott is what you are looking for.
Edit: Transposing:
int width = array.length;
int height = array[0].length;
int[][] array_new = new int[height][width];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
array_new[y][x] = array[x][y];
}
}

Why do I get an "java.lang.ArrayIndexOutOfBoundsException: 0"

What is wrong here? I get an runtime error when I run the code in Netbeans saying "java.lang.ArrayIndexOutOfBoundsException: 0"
I found out it means something like "the value does not exist" - but that is what I am trying to do - to let the user define the values for the array size. Help, please.
public static void main(String[] args) {
int row = 0;
int colum = 0;
//Declare 2d array
int [][] matrix = new int [row][colum];
//Create input for array size
Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix[row].length + " rows and " + matrix[colum].length + " colums: ");
for (row = 0; row < matrix.length; row++) {
for (colum = 0; colum < matrix[row].length ; colum++) {
matrix[row][colum] = input.nextInt();
//Input variables to array
//Print the array
for (row = 0; row < matrix.length; row++ ) {
for (colum = 0; colum < matrix[row].length; colum++ ) {
System.out.println(matrix[row][colum] + "");
}
System.out.println();
}
}
}
}
}
Two problems. You need to initialize row and column with non-zero values:
int row = 3;
int colum = 4;
You're not referencing the dimensions of the matrix correctly, you want:
System.out.println("Enter " + matrix.length + " rows and "
+ matrix[0].length + " colums: ");
There are a few more bad references further down. You could of course just use your row and column variables instead of getting the lengths from the matrix though.
For your case
int [][] matrix = new int [0][0];
Means with no element , index starts from 0, where the size you specify starts from 1
Go for ArrayList if you want dynamic array
Your array has 0 elements - you're trying to access the first (with index 0) - which is out of bounds.
You are creating an array of arrays that has size 0 in both dimensions:
int row = 0;
int colum = 0;
//Declare 2d array
int [][] matrix = new int [row][colum];
If you try to index this you will get an ArrayIndexOutOfBoundsException.
Set row and colum to something > 0.
Arrays in Java have a fixed size. Once you have created an array, you can't change the size of it. If you need to change the size at runtime, use a collection class (for example an ArrayList) instead of an array.
int row = 0;
int colum = 0;
int [][] matrix = new int [row][colum];
The declared array has zero rows and zero columns. You can't store anything in it.
The exception occurs here:
matrix[row].length
with row=0 because it is the number of columns of the first row (arrays are zero based!) which doesn't exist.
Your problem is that you're setting row and column to 0, then you create a two-dimensional array of size 0 in both directions, and then this:
matrix[row].length
fails because there is no entry at index 0 - it would require the array to have at least size 1.

Categories

Resources