How to print a 2d array in java using a single for-loop?
I tried to search answers but only found solutions using multiple loops.
Example array:
[
[1, 2, 3],
[4, 5],
[6, 7, 8],
[9]
]
Example output (the exact format does not matter):
1, 2, 3, 4, 5, 6, 7, 8, 9
With a single for-loop, not a nested loop.
So not something like this:
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
}
The principle to read a 2D array with a single loop : one [H,W] 2D matrix could be computed as a 1D matrix of HxW length.
On this basis a solution could be:
int[][] arr = {{1, 2, 3}, {4, 5, 8}, {5, 6, 7}};
int hight = arr.length;
int width = arr[0].length;
for (int i = 0; i < width * hight; i++) {
int li = i / hight;
int col = i % hight;
System.out.print(arr[li][col]);
if (col == width - 1) System.out.println();
}
Output:
123
458
567
If you need to know any algorithm for using only one loop you may try to use some like this:
public static void main(String[] args) {
int[][] arr = {{1, 2}, {3, 4}};
int currSubArrayNum = 0;
for (int i = 0; currSubArrayNum < arr.length; i++) {
System.out.println(arr[currSubArrayNum][i]);
if (i == arr[currSubArrayNum].length - 1) {
currSubArrayNum++;
i = -1;
}
}
}
Output will be next:
1
2
3
4
But if you need some simple solution for use in your program just use Arrays.toString:
public static void main(String[] args) {
int[][] arr = {{1, 2}, {3, 4}};
for (int[] anArr : arr) {
System.out.println(Arrays.toString(anArr));
}
}
With output:
[1, 2]
[3, 4]
You can define the for statement without an increment expression and transfer control of it to the inner if statement as follows:
int[][] arr = {{1, 2, 3}, {4, 5}, {6, 7, 8}, {9}};
for (int i = 0, j = 0; i < arr.length; ) {
if (arr[i] != null && j < arr[i].length) {
System.out.print(arr[i][j] + ", ");
j++;
} else {
j = 0;
i++;
}
}
Output:
1, 2, 3, 4, 5, 6, 7, 8, 9,
Create row and col pointer and update when they reach the edge.
Swift code:
func singleLoopArrayTraversal(_ data: [[Int]]) {
//Time complexity: O(n)
if data.count == 0 {
return
}
var row = 0
var col = 0
while row < data.count {
print("data[\(row)][\(col)] : \(data[row][col])")
if col == data[row].count - 1 {
row += 1
col = -1
}
col += 1
}
}
singleLoopArrayTraversal([[1, 2], [3, 4], [5, 6]])
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 need help writing a method to find out a sum of 2 different sized 2D arrays.
public static int[][] summary(int[][] tab1, int[][] tab2, int x) {
int[][] finalTab = new int[4][5]; // I took sizes of bigger one
if (x < 0) {
for (int i = 0; i < finalTab.length - 1; i++) {
for (int j = 0; j < finalTab[i].length - 1; j++) {
finalTab[i][j] = tab1[i][j] + tab2[i][j];
if (tab1[i][j] == 0) {
finalTab[i][j] = tab2[i][j];
}
}
}
for (int i = 0; i < finalTab.length; i++) {
for (int j = 0; j < finalTab[i].length; j++) {
System.out.print(" " + finalTab[i][j] + " ");
}
System.out.println();
}
}
return finalTab;
}
Input is:
int[][] tab1 = {
{2, 4, 6, 8},
{2, 4, 6, 8},
{2, 4, 6, 8}};
int[][] tab2 = {
{1, 3, 5, 7, 9},
{1, 3, 5, 7, 9},
{1, 3, 5, 7, 9},
{1, 3, 5, 7, 9}};
Output is:
3 7 11 15 0
3 7 11 15 0
3 7 11 15 0
0 0 0 0 0
Output should be:
3 7 11 15 9
3 7 11 15 9
3 7 11 15 9
1 3 5 7 9
How can I replace all of 0 with numbers corresponding to the index of tab2?
you can do it more generic
public static int[][] summary(int[][] tab1, int[][] tab2, int x) {
int maxLenX = tab1.length > tab2.length ? tab1.length : tab2.length;
int maxLenY = tab1[0].length > tab2[0].length ? tab1[0].length : tab2[0].length;
int[][] finalTab = new int[maxLenX][maxLenY]; // i took sizes of bigger one
if (x < 0) {
for (int i = 0; i <= finalTab.length - 1; i++) {
for (int j = 0; j <= finalTab[i].length - 1; j++) {
if (i > tab1.length - 1 || j > tab1[i].length - 1) {
finalTab[i][j] = tab2[i][j];
} else if (i > tab2.length - 1 || j > tab2[i].length - 1) {
finalTab[i][j] = tab1[i][j];
} else {
finalTab[i][j] = tab1[i][j] + tab2[i][j];
}
}
}
for (int i = 0; i < finalTab.length; i++) {
for (int j = 0; j < finalTab[i].length; j++) {
System.out.print(" " + finalTab[i][j] + " ");
}
System.out.println();
}
}
return finalTab;
}
so you can call it wether like that
summary(tab2, tab1, -1);
or
summary(tab1, tab2, -1);
This is a more straight-forward solution:
for (int i = 0; i < finalTab.length; i++)
for (int j = 0; j < tab1[i].length; j++) {
int v1 = (i<tab1.length && j<tab1[i].length) ? tab1[i][j] : 0;
int v2 = (i<tab2.length && j<tab2[i].length) ? tab2[i][j] : 0;
finalTab[i][j] = v1 + v2;
}
You can use IntStream.of(int...) method to concatenate two elements from different sources:
int[][] tab1 = {
{2, 4, 6, 8},
{2, 4, 6, 8},
{2, 4, 6, 8}};
int[][] tab2 = {
{1, 3, 5, 7, 9},
{1, 3, 5, 7, 9},
{1, 3, 5, 7, 9},
{1, 3, 5, 7, 9}};
int[][] tab3 = IntStream
// iterate over indices of tab2,
// because it is biggest array
.range(0, tab2.length).mapToObj(i ->
IntStream.range(0, tab2[i].length).map(j ->
// for each cell concatenate element
// from tab2 with element from tab1
// if exists, or with 0 otherwise
IntStream.of(tab2[i][j],
i < tab1.length && j < tab1[i].length ?
tab1[i][j] : 0)
// sum of two
// elements
.sum())
.toArray())
.toArray(int[][]::new);
Arrays.stream(tab3).map(Arrays::toString).forEach(System.out::println);
// [3, 7, 11, 15, 9]
// [3, 7, 11, 15, 9]
// [3, 7, 11, 15, 9]
// [1, 3, 5, 7, 9]
See also:
• Adding up all the elements of each column in a 2d array
• Rotating an int Array in Java using only one semicolon
I made it this way:
for (int i = 0; i < finalTab.length; i++)
for (int j = 0; j < finalTab[i].length; j++)
if (tab1.length > tab2.length) {
finalTab[i][j] = tab1[i][j];
} else
finalTab[i][j] = tab2[i][j];
for (int i = 0; i < tab1.length; i++) {
for (int j = 0; j < tab1[i].length; j++) {
finalTab[i][j] = tab1[i][j] + tab2[i][j];
}
}
You can use Stream#reduce method to sum two or more arrays:
public static int[][] sumArrays(int[][]... arrays) {
return Arrays.stream(arrays).reduce((arr1, arr2) -> IntStream
// iterate over the indices of
// the rows of the largest array
.range(0, Math.max(arr1.length, arr2.length))
.mapToObj(i -> IntStream
// iterate over the indices of
// the cells of the largest row
.range(0, Math.max(
i < arr1.length ? arr1[i].length : 0,
i < arr2.length ? arr2[i].length : 0))
// sum the elements of two rows if exist, or 0 otherwise
.map(j -> (i < arr1.length && j < arr1[i].length ? arr1[i][j] : 0) +
(i < arr2.length && j < arr2[i].length ? arr2[i][j] : 0))
.toArray())
.toArray(int[][]::new))
.orElse(null);
}
public static void main(String[] args) {
int[][] tab0 = {
{3, 5, 7},
{3, 5, 7}};
int[][] tab1 = {
{2, 4, 6, 8},
{2, 4, 6, 8},
{2, 4, 6, 8}};
int[][] tab2 = {
{1, 3, 5, 7, 9},
{1, 3, 5, 7, 9},
{1, 3, 5, 7, 9},
{1, 3, 5, 7, 9}};
int[][] tab3 = sumArrays(tab0, tab1, tab2);
// formatted output
Arrays.stream(tab3).map(row -> Arrays.stream(row)
.mapToObj(i -> String.format("%2d", i))
.collect(Collectors.joining(", ", "{", "}")))
.forEach(System.out::println);
}
Output:
{ 6, 12, 18, 15, 9}
{ 6, 12, 18, 15, 9}
{ 3, 7, 11, 15, 9}
{ 1, 3, 5, 7, 9}
Simply checking that i(first dimension) and j (second dimention) don't exceed the length of those of tab1, should do the trick.
private static int[][] summary(int[][] tab1, int[][] tab2, int x) {
var finalTab = new int[4][5];
if (x > 0) {
var tab1SecondDimensionLength = tab1[0].length;
for(var i = 0; i < finalTab.length; ++i) {
for(var j = 0; j < finalTab[i].length; ++j) {
var tab1Val = i < tab1.length ? j >= tab1SecondDimensionLength ? 0 : tab1[i][j] : 0;
if (tab1Val > 0) {
finalTab[i][j] = tab1Val + tab2[i][j];
} else {
finalTab[i][j] = tab2[i][j];
}
}
}
for (int i = 0; i < finalTab.length; i++) {
for (int j = 0; j < finalTab[i].length; j++) {
System.out.print(" " + finalTab[i][j] + " ");
}
System.out.println();
}
}
return finalTab;
}
Output:
3 7 11 15 9
3 7 11 15 9
3 7 11 15 9
1 3 5 7 9
I am trying to generate 2d random array similar to:
array[random][random2]
{
{1, 2},
{6, 4},
{-1, 5},
{-2}
}
the values in the array are also random, It may have -9 to -1 to 1 to 9 numbers.
Here's what i got:
public class gen2dArray {
public static void main(String args[]) {
Random random = new Random();
int n = 0;
int max = 5, min = 1;
n = random.nextInt(max - min + 1) + min;
int maxRowCol = (int)Math.pow(2,n);
int RandMaxRows = random.nextInt(maxRowCol);
int RandMaxColums = random.nextInt(maxRowCol);
int [][] array = new int [RandMaxRows][RandMaxColums];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < random.nextInt(array[i].length)+1; j++) {
array[i][j] = random.nextInt(9) + 1;
}
}
System.out.println(Arrays.deepToString(array));
}
}
Output 1:
[
[4, 4, 5, 0],
[2, 3, 0, 0]
]
Output 2:
[
[5, 2, 1, 0, 0],
[3, 4, 2, 0, 0],
[3, 1, 5, 0, 0, 0],
[4, 3, 2, 0, 0]
]
There are few problems,
Some outputs are just [[]] or []
2.
Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
at java.util.Random.nextInt(Random.java:300)
at gen2dArray.main(gen2dArray.java:23)
Getting the zeros in the array. There should be no zeros.
Output one has to be like:
[
[4, 4, 5],
[2, 3]
]
If you do not want to see the zeros, you should avoid making your arrays to big :
int [][] array = new int [RandMaxRows][];
// Code
array[value] = new int[random.nextInt(maxRowCol)];
This method should provide you an array of differents arrays of different sizes and just print out their real inputted values and not the 0 default values.
This is an example of an output :
[
[2, 4, 8, 7, 6, 6, 9],
[1, 3, 4, 2],
[1, 4, 4, 2, 7, 6, 8],
[9, 3, 6, 3, 7, 3],
[4, 5, 3, 2, 5, 2, 8]
]
Here is the modified code :
int [][] array = new int [random.nextInt(maxRowCol)][];
for (int i = 0; i < array.length; i++) {
array[i] = new int[random.nextInt(maxRowCol)];
for (int j = 0; j < array[i].length; j++) {
array[i][j] = random.nextInt(9) + 1;
}
}
When [] is printed, it means your Random did return 0.
A simple way to fix this is to add 1 to the concerned value and maybe decrease the MAX value from one also to keep the logic going.
Here is the code :
int maxRowCol = (int)Math.pow(2,n) - 1;
// Some code
int[][] array = new int [RandMaxRows + 1][];
You can simulate all these scenario by putting a System.out statement just before the array declaration.
System.out.println("RandMaxRows: " + RandMaxRows + "\tRandMaxColums: " + RandMaxColums);
Some outputs are just [[]] or []
This is happening when you are getting RandMaxRows as zero or both row and column are zero. We are using the Random.nextInt(n) for declaring the size of the array. The range of this method is 0 to n-1. So you can fix this by increment the outcome of the method.
n must be positive
This is happening when the RandMaxColums is zero. The input to the random.nextInt(n) must be greater then 0, it throws the exception.
Getting the zeros in the array. There should be no zeros.
The inner for-loop should be like this.
for (int j = 0; j < array[i].length; j++) {
You need iterate the array with it's length, for that any random number generation is not required. Use the current length and fill the array with randomly generated numbers.
Here is the work code for your problem:
public class gen2dArray {
public static void main(String args[]) {
Random random = new Random();
int n = 0;
int max = 5, min = 1;
n = random.nextInt(max - min + 1) + min;
int maxRowCol = (int)Math.pow(2,n);
int RandMaxRows = random.nextInt(maxRowCol);
int RandMaxColums = random.nextInt(maxRowCol);
System.out.println("RandMaxRows: " + RandMaxRows + "\tRandMaxColums: " + RandMaxColums);
int [][] array = new int [RandMaxRows+1][RandMaxColums+1];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
int temp = random.nextInt(9);
array[i][j] = temp + 1;
}
}
System.out.println(Arrays.deepToString(array));
}
}
Sample Output:
RandMaxRows: 3 RandMaxColums: 3
[[1, 3, 3, 3], [2, 7, 6, 1], [5, 4, 4, 1], [6, 4, 6, 9]]
Guys i have been trying to put the last value of a matrix as the first and the first value as second but this is my out come
generated matrix es:
8, 4, 10,
4, 6, 9,
3, 9, 7,
upside down matrix:
7, 9, 3, 7, 9, 3, 7, 9, 3,
this is the code:
public String segmat(int a[][]) {
String s = "";
for (int i =0;i<a.length;i++){
//for (int i = a.length - 1; i >= 0; i--) {
for (int j = a[0].length - 1; j >= 0; j--) {
s += a[a.length - 1][j] + ", ";
}
}
return s;
}
This example can be helpful for you
I commented the code so it will be quite easy to understand
public class MatrixExample {
private static int[][] reverse(int[][] matrix){
int row=matrix.length;
int column=matrix[0].length; //we have for shure this element, his length is the number of colmn
int to_return[][] = new int[row][column]; //this is a matrix of the same dimention of the original
//the indexes that will cicle the row and the column of the new matrix
int new_row=0;
int new_column=0;
for(int i=row-1;i>-1;i--){ //this will cile the rows from the last to thee first
for(int j=column-1;j>-1;j--){ //this will cicle the colums from the last to the first
to_return[new_row][new_column]=matrix[i][j];
new_column++;
}
new_column=0;
new_row++;
}
return to_return;
}
public static void main(String[] args) {
int matrix[][] = {{ 1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10,11,12}};
int[][] new_matrix = reverse(matrix);
for(int i=0;i<new_matrix.length;i++){
for(int j=0;j<new_matrix[0].length;j++){
System.out.print(new_matrix[i][j]+" ");
}
System.out.println();
}
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
So I can just use standard arrays for this, nothing else. I have to find a way to make a method that finds all the cycles in the given permutation and returns them as an array object of arrays. Then I have to place the lowest of each array as the first entry of the array. Then sort them by lowest.
I can't use arraylists or sets or anything.
EDIT: By cycles I mean take the integer value of the initial object and locate the index value that it corresponds to. Take that integer value at that index and do the same. Continue doing this until it points back to an object that's already been referenced.
An example: [0, 4, 2, 8, 7, 9, 1, 6, 5, 3]
would be these cycles : [0] [4, 8, 5, 7, 6, 9, 3, 2] [1]
and return this: [0], [1], [2, 4, 8, 5, 7, 6, 9, 3]
or
This array: [2, 4, 8, 1, 5, 3, 9, 0, 7, 6]
would be these cycles : [2, 8, 7, 0] [4, 5, 3, 1] [9, 6]
and return this : [0, 2, 8, 7], [1, 4, 5, 3], [6, 9]
I am so lost, any help would be wonderful. thanks ahead of time!
Don't ask why I took the time to do this.
EDIT: Totally working now
public class Main {
public Main()
{
}
public static void main(String[] args)
{
int array[] = {0, 4, 2, 8, 7, 9, 1, 6, 5, 3};
Main m = new Main();
int[][] cycles = m.getCycles(array);
for (int i = 0; i < cycles.length; i++)
{
System.out.print("[");
for (int j = 0; j < cycles[i].length; j++)
{
System.out.print(cycles[i][j]);
if (j < cycles[i].length - 1)
System.out.print(", ");
}
System.out.println("]");
}
System.out.println("end debug");
}
public int[][] getCycles(int[] array)
{
int[][] cycles = new int[array.length][array.length];
// initialize the cycles to all -1s, cuz they'll never be in the array
for (int i = 0; i < cycles.length; i++)
{
for (int j = 0; j < cycles[i].length; j++)
{
cycles[i][j] = -1;
}
}
int i = 0;
do {
int nextElement = array[i];
int j = 0;
do {
cycles[i][j] = nextElement;
nextElement = array[nextElement];
j++;
} while (!elementInArray(cycles[i], nextElement) && j < array.length);
i++;
} while (!arrayHasCycled(array, cycles) && i < array.length);
cycles = removeNegativeOnes(cycles, i);
for (i = 0; i < cycles.length; i++)
{
pushForward(cycles[i]);
}
return cycles;
}
public boolean elementInArray(int[] array, int element)
{
for (int i = 0; i < array.length; i++)
{
if( array[i] == element)
return true;
}
return false;
}
public int[][] removeNegativeOnes(int[][] cycles, int numCycles)
{
int [][] newCycles = new int[numCycles][];
for (int i = 0; i < numCycles; i++)
{
int realLenOfCycle = indexOf(-1, cycles[i]);
newCycles[i] = new int[realLenOfCycle];
for (int j = 0; j < newCycles[i].length; j++)
{
newCycles[i][j] = cycles[i][j];
}
}
return newCycles;
}
public int indexOf(int element, int[] array)
{
int index = -1;
for (int i = 0; i < array.length; i++)
{
if (array[i] == element)
return i;
}
return index;
}
public boolean arrayHasCycled(int[] array, int[][] cycles)
{
for (int i = 0; i < array.length; i++)
{
boolean cycleHasValue = false;
for (int j = 0; j < cycles.length; j++)
{
for (int k = 0; k < cycles[j].length; k++)
{
if (cycles[j][k] == array[i])
cycleHasValue = true;
}
}
if (!cycleHasValue)
return false;
}
return true;
}
public void pushForward(int [] array)
{
int lastElement = array[array.length - 1];
for (int i = array.length - 1; i > 0; i--)
{
array[i] = array[i - 1];
}
array[0] = lastElement;
}
}
Output:
[0]
[1, 4, 7, 6]
[2]
[3, 8, 5, 9]
From what I understand, you're asked us to create a code which executes the following algorithm:
Create a one-dimensional array of integers, array
For each element in that array, nextElement do the following:
Create a new one-dimensional array, currCycle that will be added to a two-dimensional array, cycles.
Set the first element of that array to nextElement.
nextElement then becomes array[nextElement]
If nextElement is already in currCycle, continue onto the next element of array
Check if all the elements of array are in cycles, and if so, stop executing this algorithm.
Finally, return the cycles as a two-dimensional array with the index that was being used instead of the element at that index, which is what the current array consists of. To accomplish this, just cyclically (in the normal sense) push each element of the array forward one index.
This doesn't follow your examples exactly, but I think you may have malformed your examples, for instance:
An example: [0, 4, 2, 8, 7, 9, 1, 6, 5, 3]
would be these cycles : [0] [4, 8, 5, 7, 6, 9, 3, 2] [1]
and return this: [0], [1], [2, 4, 8, 5, 7, 6, 9, 3]
The first element 0 is 0, so when you get 0, it's already in the current cycle, so go to the next element, the element at index 1, which is 4. Once you're at 4 go to the fourth element, which is 7 not 8!
0 1 2 3 4
[0, 4, 2, 8, 7...