Filling a jagged 2d array first by columns - java

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?

Related

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

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 + " ");
}
}
}
}

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?

Dividing a 1D array into a 2D array

So I have homework that asked me to:
Write a method that takes two parameters: an array of integers and an integer that represents a number of elements. It should return a two-dimensional array that results from dividing the passed one-dimensional array into rows that contain the required number of elements. Note that the last row may have less number of elements if the length of the array is not divisible by the required number of elements. For example, if the array {1,2,3,4,5,6,7,8,9} and the number 4 are passed to this method, it should return the two-dimensional array {{1,2,3,4},{5,6,7,8},{9}}.
I tried to solve it using this code:
public static int[][] convert1DTo2D(int[] a, int n) {
int columns = n;
int rows = a.length / columns;
double s = (double) a.length / (double) columns;
if (s % 2 != 0) {
rows += 1;
}
int[][] b = new int[rows][columns];
int count = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (count == a.length) break;
b[i][j] = a[count];
count++;
}
}
return b;
}
But I had a problem which is when I try to print the new array this is the output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 0, 0]]
So how can I remove the 3 zeros at the end? Just a note that I can't use any method from java.util.* or any built-in method to do this.
Change the 2D array's initialization to not contain the second dimension: new int[rows][]. Your array now has null arrays inside it. You have to initialize those in your loop: b[i]=new int[Math.min(columns,remainingCount)]; where remainingCount is the amount of numbers outside the 2d array.
Populating a 2d array with values from a 1d array as long as they are present:
public static int[][] convert1DTo2D(int[] arr, int n) {
// row count
int m = arr.length / n + (arr.length % n == 0 ? 0 : 1);
// last row length
int lastRow = arr.length % n == 0 ? n : arr.length % n;
return IntStream.range(0, m)
.mapToObj(i -> IntStream.range(0, i < m - 1 ? n : lastRow)
.map(j -> arr[j + i * n])
.toArray())
.toArray(int[][]::new);
}
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[][] arr2 = convert1DTo2D(arr1, 4);
System.out.println(Arrays.deepToString(arr2));
// [[1, 2, 3, 4], [5, 6, 7, 8], [9]]
}
See also: How to populate a 2d array with values from a 1d array?
It may be better to switch arguments in the method:
int[][] convert1DTo2D(int cols, int... arr)
to allow use of vararg.
Also, it is possible to iterate on the input array (single loop) instead of nested loops.
Example implementation:
public static int[][] convert1DTo2D(int cols, int... a) {
int lastRowCols = a.length % cols;
int rows = a.length / cols;
if (lastRowCols == 0) {
lastRowCols = cols;
} else {
rows++;
}
int[][] b = new int[rows][];
for (int i = 0; i < a.length; i++) {
int r = i / cols;
int c = i % cols;
if (c == 0) { // start of the row
b[r] = new int[r == rows - 1 ? lastRowCols : cols];
}
b[r][c] = a[i];
}
return b;
}
Adding this if-condition to your code will shorten the final array should it not be the right size:
...
final int[][] b = new int[rows][columns];
if ((a.length % columns) != 0) {
b[rows - 1] = new int[a.length % columns];
}
int count = 0;
...
% is the Modulo operator which gives you the remainder of a division of the first and second number.
9 % 4 would return 1, the exact size needed for our final array.
We then merely have to replace the final array with a new one of that size.

Adding each column inside a Jagged array not working

I have been recently working with 2D and Jagged Arrays and am trying to add each element in a row and each element inside a column. I got the code to print out the sum of each row, but am having difficulty with adding each column in the array.
Note: I tried doing sum += numbers[c][r]; but it is not working
import java.util.Arrays;
import java.io.*;
public class Homework{
public static void main(String[] args) {
int[][] numbers = { {3, 2, 5,},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };
//Adding each row in the array
int sum = 0;
for(int r = 0; r < numbers.length; r++) {
sum = 0;
for(int c = 0; c < numbers[r].length; c++) {
sum += numbers[r][c];
}
System.out.println("Sum of row: " + sum);
}
//Adding each column in the row
int sum2 = 0;
for(int r = 0; r < numbers.length; r++) {
sum2 = 0;
for(int c = 0; c < numbers[r].length; c++) {
sum2 += numbers[c][r];
}
System.out.println("Sum of column: " + sum2);
}
}
}
Okay so you were sort of on the right track. Let me explain a way of thinking before I get into the code.
You have a non-square 2d Array and you want the total of each row and column. Row is simple, you've accomplished that already. Column is a little more difficult because since its non-square, you will run into ArrayOutOfBoundsExceptions because it tries to access a art of the array that doesn't exist.
To combat this, you need to know the max number of columns there are and then iterate through the array. BUT, you also need to be careful about that ArrayOutOfBoundsException, making sure to account for when the current column iteration is greater than the row length.
I added an int max to your row sum section, this way I don't have to iterate over the same info more than once.
After that, I replace c < numbers[r].length with 'max', since we need to iterate over X columns.
Then I iterate over the rows, since they are uniform and easily found by numbers.length.
So, a simple change to your code yields the results you need. See below.
int[][] numbers = {
{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}
};
int max = 0;
//Adding each row in the array
int sum;
for(int r = 0; r < numbers.length; r++) {
sum = 0;
for(int c = 0; c < numbers[r].length; c++) {
sum += numbers[r][c];
if(numbers[r].length > max){
max = numbers[r].length;
}
}
System.out.println("Sum of row: " + sum);
}
System.out.println("Max " + max);
//Adding each column in the row
int sum2;
for(int c = 0; c < max; c++) {
sum2 = 0;
for(int y = 0; y < numbers.length; y++){
if(numbers[y].length > c){
sum2 += numbers[y][c];
System.out.println(numbers[y][c]);
}
}
System.out.println("Sum of column: " + sum2);
}
}

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