How do we do sum of indexes in a 2D array - java

I have a 2D array where rows = 3 and columns = 2. I want to get a sum of all the indices. Here is my array.
arr[][] = [1, 2], [3, 4], [5, 6]
Row 1
At index (0, 0) the sum of indexes becomes (0 + 0 = 0)
At index (0, 1) the sum of indexes becomes (0 + 1 = 1)
Row 2
At index (1, 0) the sum of indexes becomes (1 + 0 = 1)
At index (1,1) the sum of indexes becomes (1 + 1 = 2)
Row 3
At index (2, 0) the sum of indexes becomes (2 + 0 = 2)
At index (2, 1) the sum of indexes becomes (2 + 1 = 3)
My expected output becomes
0 1 1 2 2 3
I am unable to find any resource, how to do this

Another quick example:
import java.util.*;
class Main {
public static void main(String[] args) {
int[][] arr = new int[3][2];
for(int row=0; row<arr.length; row++) {
for(int col=0; col<arr[row].length; col++) {
arr[row][col] = row + col;
}
}
for(int[] row : arr) {
System.out.println(Arrays.toString(row));
}
}
}
Output:
[0, 1]
[1, 2]
[2, 3]

You have to do sum of column and row using for loop or any other loop.
import java.util.*;
public class Main
{
public static void main(String[] args) {
int rows, cols, sumIndex = 0;
int a[][] = {
{1, 2},
{3, 4},
{5, 6}
};
rows = a.length;
cols = a[0].length;
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
sumIndex = i + j;
System.out.print(sumIndex + " ");
}
}
}
}

Related

Calculating the sum for each array column

I have a 2d-array data, as an example I choose those numbers:
int[][] data = {
{1, 2, 3, 4},
{1, 2, 3, 4},
{1, 2, 3, 4}};
For each column I want to add the sum of numbers together and save them in seperate integers.
This is the result im looking for:
c_zero = 3;
c_one = 6;
c_two = 9;
c_three = 12;
This is the code I have thus far:
int c_zero = 0;
int c_one = 0;
int c_two = 0;
int c_three = 0;
for (int a = 0; a < data.length; a++) {
for (int b = 0; b < data.length; b++) {
for (int[] row : data)
for (int value : row) {
if (int[] row == 0) { //this does not work
c_zero += value;
}
if (int[] row == 1) { //this does not work
c_one += value;
}
...
}
}
}
How can I get the values for each row in a specific row?
I would create a 1D integer array and use that to store the running sum for each column:
int[][] data = {{1,2,3,4},
{1,2,3,4},
{1,2,3,4}};
int[] colSums = new int[data[0].length];
for (int r=0; r < data.length; ++r) {
for (int c=0; c < data[r].length; ++c) {
colSums[c] += data[r][c];
}
}
System.out.println(Arrays.toString(colSums)); // [3, 6, 9, 12]
Using Java 8, you can apply the reduce method to the stream over the rows of a 2d array to sum the elements in the columns and produce a 1d array of sums.
// array must not be rectangular
int[][] data = {
{1, 2, 3, 4},
{1, 2, 3, 4},
{1, 2, 3, 4, 5}};
int[] sum = Arrays.stream(data)
// sequentially summation of
// the elements of two rows
.reduce((row1, row2) -> IntStream
// iterating over the indexes of the largest row
.range(0, Math.max(row1.length, row2.length))
// sum the elements, if any, or 0 otherwise
.map(i -> (i < row1.length ? row1[i] : 0)
+ (i < row2.length ? row2[i] : 0))
// array of sums by column
.toArray())
.orElse(null);
// output of an array of sums
System.out.println(Arrays.toString(sum));
// [3, 6, 9, 12, 5]
// output by columns
IntStream.range(0, sum.length)
.mapToObj(i -> "Column " + i + " sum: " + sum[i])
.forEach(System.out::println);
//Column 0 sum: 3
//Column 1 sum: 6
//Column 2 sum: 9
//Column 3 sum: 12
//Column 4 sum: 5
See also:
• Adding up all the elements of each column in a 2d array
• How to create all permutations of tuples without mixing them?

Filling a jagged 2d array first by columns

I want to write a function that takes an 2d array and fills it with 1...n but counting the columns first instead of the rows:
input = {{0, 0, 0, 0}, {0}, {0}, {0, 0}};
the output should be: {{1, 5, 7, 8}, {2}, {3}, {4, 6}};
if i were to loop through rows and then colums i get:
private static void fill1(int[][] input) {
int count = 1;
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input[i].length; j++) {
input[i][j] = count;
count++;
}
}
}
How do I loop through colums first?
You can do this by first transposing your input, executing your fill1 code and then transposing the output again.
See this question for how to transpose a 2 dimensional array in Java: java multi-dimensional array transposing
If you were dealing with a regular 2d matrix, where all the rows had the same number of columns, the code would be a simple modification of the code for filling the matrix row-by-row:
private static void fill1(int[][] input) {
int count = 1;
for (int j = 0; j < input[0].length; j++) {
for (int i = 0; i < input.length; i++) {
input[i][j]= count;
count++;
}
}
}
The process is basically the same for a ragged 2d array, but with a couple added twists:
You need to do some extra work to figure out how many columns there could be (i.e., the maximum row length)
You need to be prepared for the case when there's no cell at a given row/column position.
The following modification of the previous code addresses these issues:
private static void fill1(int[][] input) {
int maxCols = input[0].length;
for (int i = 1; i < input.length; ++i) {
if (input[i].length > maxCols) {
maxCols = input[i].length;
}
}
int count = 1;
for (int j = 0; j < maxCols; j++) {
for (int i = 0; i < input.length; i++) {
if (j < input[i].length) {
input[i][j]= count;
count++;
}
}
}
}
To iterate first over the columns of a jagged 2d array to fill it, you have to know the maximum number of columns beforehand, but if you don't know that, you can iterate to the Integer.MAX_VALUE and check at each step if the columns are still present or not:
int[][] arr = {{0, 0, 0, 0}, {0}, {0}, {0, 0}};
int count = 1;
for (int col = 0; col < Integer.MAX_VALUE; col++) {
boolean max = true;
for (int row = 0; row < arr.length; row++) {
if (col < arr[row].length) {
arr[row][col] = count;
count++;
max = false;
}
}
if (max) break;
}
for (int[] row : arr) {
System.out.println(Arrays.toString(row));
}
Output:
[1, 5, 7, 8]
[2]
[3]
[4, 6]
See also: How do you rotate an array 90 degrees without using a storage array?
To populate a 2d array first by columns, you can use two nested streams. In case of a jagged 2d array, when you don't know beforehand the number of the columns in each row, in an outer stream you can traverse while the columns are still present.
/**
* #param arr array that should be populated.
* #return maximum row length, i.e. columns count.
*/
private static long populate(int[][] arr) {
AtomicInteger counter = new AtomicInteger(1);
return IntStream
// traverse through the array columns
.iterate(0, i -> i + 1)
// process the array rows where
// this column is present
.mapToLong(i -> Arrays.stream(arr)
// filter those rows where
// this column is present
.filter(row -> row.length > i)
// assign a value to the element and increase the counter
.peek(row -> row[i] = counter.getAndIncrement())
// count of rows where this column is present
.count())
// while the columns are still present
.takeWhile(i -> i > 0)
// max columns count
.count();
}
public static void main(String[] args) {
int[][] arr = {{0, 0, 0, 0, 0, 0}, {0, 0}, {0}, {0, 0, 0}};
System.out.println("Max columns count: " + populate(arr));
System.out.println(Arrays.deepToString(arr));
}
Output:
Max columns count: 6
[[1, 5, 8, 10, 11, 12], [2, 6], [3], [4, 7, 9]]
See also: How to create a new List from merging 3 ArrayLists in round robin style?

How to check number of rows with only 0 on 3D matrix?

I need to count how many rows does the user inputs that are only 0, something like:
Test 1
0 0 0
1 2 3
2 2 1
Test 2
1 2 3
0 0 0
0 0 0
Rows with only 0 values: 3
This is the code that reads the matrices:
final int rows = 3, cols = 3;
Scanner input = new Scanner(System.in);
System.out.println("Number of tests");
int n = input.nextInt();
int test[][][] = new int[n][rows][cols];
for (int i = 0; i < n; i++) {
System.out.println("Test " + (i + 1));
for (int j = 0; j < rows; j++) {
for (int k = 0; k < cols; k++) {
test[i][j][k] = input.nextInt();
}
}
}
You can get the number of zero rows in a 3D matrix using Streams as follows:
public static void main(String[] args) {
int[][][] test = {
{{0, 0, 0}, {1, 2, 3}, {2, 2, 1}},
{{1, 2, 3}, {0, 0, 0}, {0, 0, 0}}};
System.out.println(zeroRowsCount(test)); // 3
}
public static long zeroRowsCount(int[][][] arr3d) {
return Arrays.stream(arr3d)
// the number of zero rows in each 2D array
.mapToLong(arr2d -> zeroRowsCount(arr2d))
// total number of zero rows
.sum();
}
public static long zeroRowsCount(int[][] arr2d) {
return Arrays.stream(arr2d)
// filter those rows that consist of zeros
.filter(row -> Arrays.stream(row)
// all elements are zeros
.allMatch(i -> i == 0))
// the number of zero rows
.count();
}

How to organize columns of 2D array based on sum of columns?

I would like to organize a 2D array in descending order of each columns sum. For example:
3 1 1
2 6 5
5 4 2
The sum of column 1 would be 10, column 2 would be 11, column 3 would be 8. Columns 2 and 1 would need to switch to be sorted in descending order. The updated 2D array would be:
1 3 1
6 2 5
4 5 2
I'm aware of Collections.reverseOrder(), but that only works on sorting 1D arrays in descending order.
Here is the code I am using to get the sum of each column:
int tempSum = 0;
for (int i = 0; i < columns; i++) {
for (int j = 0; j < rows; j++) {
tempSum = array[i][j]
}
//reset tempSum
tempSum = 0;
}
I am currently not doing anything with the tempSum of each column. Any guidance would be great.
Try this.
int[][] transpose(int[][] matrix) {
int rows = matrix.length, cols = matrix[0].length;
int[][] transposed = new int[cols][rows];
for (int r = 0; r < rows; ++r)
for (int c = 0; c < cols; ++c)
transposed[c][r] = matrix[r][c];
return transposed;
}
And
int[][] m = {
{3, 1, 1, 9},
{2, 6, 5, 4},
{5, 4, 2, 6}};
m = transpose(m);
Arrays.sort(m, Collections.reverseOrder(Comparator.comparingInt(row -> IntStream.of(row).sum())));
m = transpose(m);
for (int[] row : m)
System.out.println("\t" + Arrays.toString(row));
output
[9, 1, 3, 1]
[4, 6, 2, 5]
[6, 4, 5, 2]
Or if you need more performance
m = transpose(m);
m = Arrays.stream(m)
.map(row -> new Object() {
int sum = IntStream.of(row).sum();
int[] origin = row;
})
.sorted((a, b) -> Integer.compare(b.sum, a.sum))
.map(obj -> obj.origin)
.toArray(int[][]::new);
m = transpose(m);

Compare elements of a matrix by java columns

I have the following code and the following doubt about the route of the column of a matrix, comparing with the previous one, later and others. I take the first column from top to bottom. I take the first element and compare if they are the same as the next one (below). This second position of the column, compares if they are the same with the one above and the one below, and so on with the third one. I mean, if I have this column:
1
2
2
2
3
2
2
2
2
1
If you have 3 or more identical contiguous numbers, I have to set them to 0 (that's what I think it would do). The output would be:
1
0
0
0
3
0
0
0
0
1
This I need to do with each column, I have this method and I want to do it in the simplest way, the most direct solution without strange things, although I'm thinking that it has to be recursive anyway, I do not know. The only thing that makes me is to create a matrix of zeros and I can not find the fault.
Code:
public static void matrix(int[][] matrix, int size, int[] color, int position) {
int repeated = 0;
for (int row = 1; row < size; row ++) {
for (int col = 1; col < size; col++) {
if (matrix[row][col] == matrix[row][col++]) {
repeated = matrix[row][col];
}
while (matrix[row][col] == repeated) {
matrix[row][col] = 0;
row++;
}
}
}
Here is the code I constructed for your scenario. You can find helpful comments within the code.
public static void main(String[] args)
{
int matrix[][] = new int[][]{
{1,2},
{2,2},
{2,2},
{2,2},
{3,2},
{2,2},
{2,2},
{2,3},
{2,1},
{1,3}};
matrix(matrix, 10, null, 0);
System.out.println(matrix);
}
public static void matrix(int[][] matrix, int size, int[] color, int position) {
//This value keeps track of the current value checked for repetition
int repeated = 0;
//The running total for repeated
int count = 1;
//My matrix create with 2 columns,
for (int col = 0; col < 2; col ++) {
//initialized - may need length check
repeated = matrix[0][col];
count = 1;
for (int row = 1; row < size; row++) {
if (matrix[row][col] == repeated)
{
count++;
}
else
{
//reset the values when match fails
count = 1;
repeated = matrix[row][col];
}
if(count == 3)
{
//First score of 3
matrix[row][col] = 0;
matrix[row-1][col] = 0;
matrix[row-2][col] = 0;
}
else if(count > 3)
{//Scoring after 3
matrix[row][col] = 0;
}
}
}
}
Here is the output
[[1, 0],
[0, 0],
[0, 0],
[0, 0],
[3, 0],
[0, 0],
[0, 0],
[0, 3],
[0, 1],
[1, 3]]

Categories

Resources