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?
Related
I'm trying to sort selected column. I have generated array with random numbers. This is my code to print selected column for example I'm trying to select 1st row = min.
int column = 10,
row = 10,
min = 1 ,
max = 9;
for (int i = 0; i < arr.length; i = i + 1) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = (int)(Math.random()*(max - min) + min);
System.out.printf("%2d", arr [i][j]);
}
}
for (int k = 0 ; k < column ; k++) {
System.out.print(arr[min][k]);
}
I have tried doing something like this to sort:
for (int k = 0 ; k < column ; k++) {
for (int j = k + 1 ; j < arr.length; j++) {
if (arr[k][min] > arr[j][min]) {
int[] temp = mas[k];
arr[k] = arr[j];
arr[j] = temp;
}}
System.out.print(arr[min][k]);}
Just use the Arrays#sort() method with a comparator like this (Java8+). Here are examples sorting a specific column in Ascending and Descending order. Only works with a Matrix where all array columns are of equal length as demonstrated:
Ascending Order:
int[][] myInt2DArray = {{2, 1, 4, 6},
{5, 3, 7, 1},
{1, 2, 3, 4},
{6, 9, 2, 8}};
// Sort in Ascending Order based on 4th column (column index 3):
int columnIndexToSort = 3;
// Sort the Array:
Arrays.sort(ary, (a, b) -> a[columnIndexToSort] - b[columnIndexToSort]);
// Display Array in Console:
for (int[] array : myInt2DArray) {
System.out.println(Arrays.toString(array));
}
Output to Console Window (note the fourth data column):
[5, 3, 7, 1]
[1, 2, 3, 4]
[2, 1, 4, 6]
[6, 9, 2, 8]
Descending Order:
// Sort in Descending Order based on 3rd column (column index 2):
columnIndexToSort = 2;
// Sort the Array:
Arrays.sort(ary, (a, b) -> b[columnIndexToSort] - a[columnIndexToSort]);
// Display Array in Console:
for (int[] array : myInt2DArray) {
System.out.println(Arrays.toString(array));
}
Output to Console Window (note the third data column):
[5, 3, 7, 1]
[2, 1, 4, 6]
[1, 2, 3, 4]
[6, 9, 2, 8]
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 + " ");
}
}
}
}
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?
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);
I am trying to reverse a multidimensional array where the amount of columns in each row are not the same.
Right now, I've managed to reverse the array in the example, but what if column size change in each row? lets say the array consist of {{1},{1,2,3}, {1,2}.......} is there a smarter way to do this without using if-statements for each row?
int[][] array3 = new int[3][4];
int[][] array4 = {{1,2,3},{7,8,6},{3,2,1,0}};
int counter = 2;
for(int row=0; row<array4.length; row++)
{
if(row == 2)
counter = 3;
for(int col=0; col<array4[row].length; col++)
{
array3[row][counter] = array4[row][col];
counter--;
}
counter = 2;
}
You can use two simple for loops iterating over the arrays and creating a new one:
int[][] reversed = new int[array.length][];
for (int i = 0; i < array.length; i++) {
int[] row = array[array.length - i - 1];
reversed[i] = new int[row.length];
for (int j = 0; j < row.length; j++) {
reversed[i][j] = row[row.length - j - 1];
}
}
With Java Streams you can use this, which does the same:
int[][] reversed = IntStream.rangeClosed(1, array.length)
.mapToObj(i -> array[array.length - i])
.map(row -> IntStream.rangeClosed(1, row.length)
.map(i -> row[row.length - i])
.toArray())
.toArray(int[][]::new);
For the input array you showed:
int[][] array = {{1, 2, 3}, {7, 8, 6}, {3, 2, 1, 0}};
The result with both solutions will be this:
[[0, 1, 2, 3], [6, 8, 7], [3, 2, 1]]