I'm having a problem printing columns. When the code reaches "100" it stops reading what is below it because it's empty:
public class Column{
public static void main( String[] arg )
{
int[][] uneven =
{ { 1, 3, 100, 6, 7, 8, 9, 10},
{ 0, 2},
{ 0, 2, 4, 5},
{ 0, 2, 4, 6, 7},
{ 0, 1, 4, 5 },
{ 0, 1, 2, 3, 4, 5, 6 }};
for ( int col=0; col < uneven.length; col++ )
{
System.out.print("Col " + col + ": ");
for( int row=0; row < uneven.length; row++ )
System.out.print( uneven[row][col] + " ");
System.out.println();
}
}
}
What should I do so that it will continue reading the column?
To print a variable length 2-D array, your inner loop runs from 0 to the current row length : -
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) { // Closely see inner loop
System.out.println(arr[i][j]);
}
}
arr[i] is the current row. And arr[i].length gives the number of columns in that row.
You can infer it like this: -
arr is a 2-D array.
So, each element of your arr is a 1-D array.
So, arr[i] is a 1-D array. Which represents each row.
To get number of columns in each row, you do arr[i].length
Now, you can apply the same thing in your problem.
Actually, your for loop is running wrongly. Your outer loop is running from col = 0 to col < uneven.length, but it should run from: - row = 0 to row < uneven.length
So, your for loop should be like: -
for ( int row=0; row < uneven.length; row++ )
{
System.out.print("Row " + row + ": ");
for( int col=0; col < uneven[row].length; col++ ) {
System.out.print( uneven[row][col] + " ");
}
System.out.println();
}
UPDATED : -
Ok, I got your question wrong first. If you want to print column wise, you can use this code: -
int[][] uneven =
{ { 1, 3, 100, 6, 7, 8, 9, 10},
{ 0, 2},
{ 0, 2, 4, 5},
{ 0, 2, 4, 6, 7},
{ 0, 1, 4, 5 },
{ 0, 1, 2, 3, 4, 5, 6 }};
int max = -1;
for ( int row = 0; row < uneven.length; row++ ) {
if (uneven[row].length > max) {
max = uneven[row].length;
}
}
System.out.println(max);
for (int i = 0; i < max; i++) {
for (int j = 0; j < uneven.length; j++) {
if (uneven[j].length <= i) {
continue;
}
System.out.print(uneven[j][i] + " ");
}
System.out.println();
}
First you need to find the max among all number of columns in each row.
Then run the loop again, from 0 to max columns. Now, since you have a lop for columns, now you need another one for rows. And that will be your inner loop.
Now, in inner loop, you cannot just print the array element at the (j, i) index, because the current row might not have max number of columns. So, you need to put an if-condition to check that.
Replace:
for( int row=0; row < uneven.length; row++ )
with:
for( int row=0; row < uneven[col].length; row++ )
Related
I have a 2D Array:
{0, 0, 1, 1, 1},
{0, 0, 1, 1, 1},
{0, 0, 1, 1, 1},
{0, 1, 0, 0, 1}
and I am trying to see which row has the closest 1 to the left, in this case it is index 3. So we have to return 3 to console, but I don't know how to go about comparing the values, etc.
This is what I have tried so far:
int array[][] = {
{0, 0, 1, 1, 1},
{0, 0, 1, 1, 1},
{0, 0, 1, 1, 1},
{0, 1, 0, 0, 1}
};
int count = 0;
Map<Integer, Integer> countMap = new HashMap<>();
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[i].length; j++){
if(array[i][j] != 1){
count++;
}else{
System.out.println("index of i: " + i + ", index of j:" + j + ", count: " + count);
countMap.put(j, count);
count = 0;
break;
}
}
}
System.out.println();
You can try to iterate in a column wise manner and return result as soon as you encounter the first '1'. This way you don't need to spend extra computation iterating through the whole 2D matrix.
public class ClosestOne {
public static int closestOne(int[][] a) {
for(int i = 0; i < a[0].length; i++) {
for(int j = 0; j < a.length; j++) {
if(a[j][i] == 1) {
return j;
}
}
}
return -1;
}
public static void main(String[] args) {
int array[][] = {
{0, 0, 1, 1, 1},
{0, 0, 1, 1, 1},
{0, 0, 1, 1, 1},
{0, 1, 0, 0, 1}
};
int closestRow = closestOne(array);
if(closestRow == -1) {
System.out.println("'1' is not present in matrix!");
} else {
System.out.println("Closest '1' is in row: " + closestRow );
}
}
}
Using a HashMap is completely over-engineered here. Theoretically you do not need any kind of data structure since you calculate the values row-by-row anyways, but since you were using one, I thought I would use one, too.
Use a simple array instead of the Map, with the length of the original array (i.e. the rows). Fill that array with a number that is higher than any result can be, to be safe I used Integer.MAX_VALUE.
int[] firstIndex = new int[array.length];
//for all i in length of array:
firstIndex[i] = Integer.MAX_VALUE;
No iterate though your your 2d array like you are and overwrite the firstIndex if you find something that is better than the current value.
//for every row
//for ever column (col)
if (array[row][col] == 1 && col < firstIndex[row]) {
firstIndex[row] = col;
}
Then in the end look for the minimum value in that array.
int min = firstIndex[0];
for (int row = 1; row < firstIndex.length; row++) {
min = Integer.min(min, firstIndex[row]);
}
System.out.println(min);
It looks like you have already worked out the count to the first 1 on each row, you just need to decide which is the lowest after completing your loop. You don't need a map to do that, just check if the current row is better than the "best so far" and if it is then update the best.
There is actually no need for a count variable since j is the same thing, and i is the row.
int best = -1; // Initialize to -1 which is an invalid index
int bestCount = Integer.MAX_VALUE; // Initialize to a very bad best count.
for(int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (array[i][j] == 1 && j < bestCount) {
best = i; // the row
bestCount = j; // the '1'
break;
}
}
}
System.out.println("Closest 1 to left in row " + best);
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 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);
}
}
I'm writing a program so that it computes and prints the sum of each column of the array. The given data looks like this:
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
Ideally, it should output the results 13, 9, 15, 13, 12, -8. But since some of the rows have different lengths, when I run my program, it outputs 13, 9, 15 and gives me an ArrayIndexOutOfBoundsException. And I really don't know how to fix it.
Here is my code:
public class ColumnSums
{
public static void main(String[] args) {
//The given data
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
//Determine the number of data in the longest row
int LongestRow = 0;
for ( int row=0; row < data.length; row++){
if ( data[row].length > LongestRow ){
LongestRow = data[row].length;
}
}
System.out.println("The longest row in the array contains " + LongestRow + " values"); //Testing
//Save each row's length into a new array (columnTotal)
int[] columnTotal = new int[4];
//Scan through the original data again
//Record each row's length into a new array (columnTotal)
System.out.println("The lengths of each row are: ");
for ( int i = 0; i < data.length; i++){
columnTotal[i] = data[i].length;
System.out.println(columnTotal[i]); //Testing
}
// Create an array to store all the sums of column
int ColumnSums[] = new int[LongestRow];
System.out.println("The sums of each column are: ");
for ( int i = 0; i < LongestRow; i++ ){
int sum = 0;
for (int j = 0; j < data.length; j++) {
sum = sum + data[j][i];
}
ColumnSums[i] = sum;
System.out.println("Column " + i + ": " + ColumnSums[i]); //Testing
}
}
}
Thanks for your time!!!
You basically just need to loop through the columns until the counter is out of bounds for every row. No need to loop through ahead of time to find the longest row.
public static ArrayList<Integer> getCollumnSum() {
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
int col = 0;
ArrayList<Integer> totals = new ArrayList<Integer>();
while (true) {
int total = 0;
boolean dataInCol = false;
for (int i = 0; i < data.length; i++) {
if (col < data[i].length) {
total += data[i][col];
dataInCol = true;
}
}
col += 1;
if (dataInCol) {
totals.add(total);
} else {
break;
}
}
return totals;
}
Output:
[13, 9, 15, 13, 12, -8]
To read a 2D array your loops should be
for(int i = 0; i < array.length; ++i){
for(int j = 0; j < array[i].length; ++j){
System.out.println(array[i][j]);
}
}
See the use of for(int j = 0; j < array[i].length; ++j) to use the current row length.
With this, you will prevent this ArrayIndexOutOfBoundsException
I am open to question if you need. Just post a comment !
I have altered your code to fit your needs
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
int longestRow = 0;
for ( int row=0; row < data.length; row++){
if ( data[row].length > longestRow ){
longestRow = data[row].length;
}
}
System.out.println("The longest row in the array contains " + longestRow + " values");
Here, no need for columnTotal as I can't notice any use of it. It maybe your program need. Anyway, you can print the length of each row directly as below.
System.out.println("The lengths of each row are: ");
for ( int i = 0; i < data.length; i++){
System.out.println("Row " + i + " is " + data[i].length);
}
You can't get the sum of each column at each inner loop, because the sum of each column will be obtained after the both loops finish. Therefore, the variable sum is useless. So, it would be like below
int columnSums[] = new int[longestRow];
for ( int i = 0; i < data.length; i++ ){
for (int j = 0; j < data[i].length; j++){
columnSums[j] +=data[i][j];
}
}
Finally, you can print the sum of each column as below
System.out.println("The sums of each column are: ");
for (int i = 0; i < columnSums.length; i++) {
System.out.println("Column " + i + ": " + columnSums[i]);
}
After running the code, the output would be:
The longest row in the array contains 6 values
The lengths of each row are:
Row 0 is 3
Row 1 is 5
Row 2 is 4
Row 3 is 6
The sums of each column are:
Column 0: 13
Column 1: 9
Column 2: 15
Column 3: 13
Column 4: 12
Column 5: -8
I need to print a 2 dimensions array with some numbers on the left side and on the bottom.
Here is my code for the initialization, wich is in the class Grille :
class Grille {
String[][] grille = new String[7][8];
public Grille() {
for (int line = 0; line < grille.length; line++) {
for (int column = 0; column < grille[column].length; column++) {
grille[line][column] = " ";
}
}
}
I print my array with this, in the same class Grille:
public void print() {
for (int line = 0; line < grille.length; line++) {
for (int column = 0; column < grille[line].length; column++) {
System.out.print(grille[line][column] + " ");
}
System.out.println("");
}
}
I would like to obtain this:
6
5
4
3
2
1
1 2 3 4 5 6 7
there are spaces between numbers in horizontal lines to make the difference and to know that they arre not in the same column
thank you!!
This task is fairly straight-forward. If you have a Two-Dimensional array, print array[I][0] until you reach array.length.
Then starting at J = 0, print array[I][J] until you reach array[i].length. Where I is the index of the last row.
The following code will print:
6
5
4
3
2
1
1 2 3 4 5 6
The code is:
public static void main(String[] args) {
int array[][] =
{
{6, 0, 0, 0, 0, 0},
{5, 0, 0, 0, 0, 0},
{4, 0, 0, 0, 0, 0},
{3, 0, 0, 0, 0, 0},
{2, 0, 0, 0, 0, 0},
{1, 2, 3, 4, 5, 6}
};
int array2[][] =
{
{6},
{5},
{4},
{3},
{2},
{1, 2, 3, 4, 5, 6}
};
print(array);
System.out.println("\n");
print(array2);
}
public static void print(int[][] array) {
for (int i = 0; i < array.length; ++i) {
if (i == array.length - 1) {
System.out.print(array[i][0] + "\n ");
for (int j = 0; j < array[i].length; ++j) {
System.out.print(array[i][j] + " ");
}
}
else {
System.out.println(array[i][0]);
}
}
}
boolean b=true;
for(int i=0;i<array.length;i++)
{
for(int j=0;j<=i;j++)
{
if(i==array.length-1)
{
if(b)
{
System.out.print(array[i][0]+"\n");
b=false;
}
System.out.print(" "+array[i][j]);
}
else
{
System.out.print(array[i][j]);
break;
}
}
System.out.print("\n");
}