switching columns of a 2d array - java

so my problem is that i cannot get the elements of a 2d array to switch like i would be able to do in a single variable array. Instead of switching the elements they are just being continuously rewritten...
for (int column = 0; column < m[0].length; column++) {
shufcol = (int)(Math.random()*4);
temp = column;
System.out.println(shufcol);
for(int row = 0; row < m.length; row++) {
temp = row;
m[row][temp]=m[row][column];
m[row][column]= m[row][shufcol];
m[row][temp] = m[row][shufcol];
}
}
input array (3X4)
{{0 1 2 3}
{1 4 5 6}
{0 7 8 9}}
output array
{{2 2 3 2}
{5 5 6 5}
{8 8 9 8}}
If your curious about the math.random, that is just to generate a random column between 0 to 3 to switch with. Again the issue is why is it only rewriting elements and not switching them?

I don't fully understand what you want to achieve at the end (because you haven't told), but I think, if you reread this piece of code:
temp = row;
m[row][temp]=m[row][column];
m[row][column]= m[row][shufcol];
m[row][temp] = m[row][shufcol];
several times and try to execute it with piece of paper and pen you'll find the mistake.

If I understood, this will switch the values in column and shufcol for all rows (I didn't test it):
for (int column = 0; column < m[0].length; column++) {
shufcol = (int)(Math.random()*4);
System.out.println(shufcol);
for(int row = 0; row < m.length; row++) {
temp = m[row][shufcol];
m[row][shufcol] = m[row][column];
m[row][column] = temp;
}
}

This will switch elements inside their rows:
//input array (3X4) {{0 1 2 3} {1 4 5 6} {0 7 8 9}}
int[][] m = {{0, 1, 2, 3}, {1, 4, 5, 6}, {0, 7, 8, 9}};
for (int column = 0; column < m[0].length; column++) {
int shufcol = (int)(Math.random()*4);
int shufrow = (int)(Math.random()*3); //need row to switch with, too
for(int row = 0; row < m.length; row++) {
if(row == shufrow){
int tempField =m[row][column];
m[row][column]= m[row][shufcol];
m[row][shufcol] = tempField;
System.out.println("In row " + row + " : column " + column + " was switched with column " + shufcol + "!");
break; //just switch once per row, easier debugging ^^-d
}
}
}
//print output array
for(int row = 0; row < m.length; row++) {
String line = "\n";
for (int column = 0; column < m[0].length; column++) {
line += m[row][column] + " ";
}
System.out.print(line);
}
Output:
In row 2 : column 0 was switched with column 2!
In row 0 : column 1 was switched with column 2!
In row 1 : column 2 was switched with column 3!
In row 0 : column 3 was switched with column 2!
0 2 3 1
1 4 6 5
8 7 0 9
Since i am not totally sure what you want to do, here is switching elements in the whole array randomly:
//input array (3X4) {{0 1 2 3} {1 4 5 6} {0 7 8 9}}
int[][] m = {{0, 1, 2, 3}, {1, 4, 5, 6}, {0, 7, 8, 9}};
for (int column = 0; column < m[0].length; column++) {
int shufcol = (int)(Math.random()*4);
int shufrow = (int)(Math.random()*3); //need row to switch with, too
//there is no point in duplicating the count variable of a loop!
System.out.println(shufcol);
for(int row = 0; row < m.length; row++) {
//check that random field is not current field!
if(row != shufrow && column != shufcol){
//switch current with random
int temp = m[row][column]; // le backuppe
m[row][column] = m[shufrow][shufcol]; // write le new value of "random source field" to current field
m[shufrow][shufcol] = temp; // write value of current field to "random source field"
System.out.println("switched [" + row + "][" + column + "] with [" + shufrow + "]["+ shufcol + "]");
break; // use break to switch only once per row, easier debugging ^^-d
}
else {
System.out.println("will not switch with self!");
}
}
}
//print output array
for(int row = 0; row < m.length; row++) {
String line = "\n";
for (int column = 0; column < m[0].length; column++) {
line += m[row][column] + " ";
}
System.out.print(line);
}
Yielding the following output:
2
switched [0][0] with [2][2]
0
switched [0][1] with [1][0]
0
switched [0][2] with [2][0]
2
switched [0][3] with [1][2]
8 1 0 5
1 4 3 6
2 7 0 9
Hope this helps! ^^-d

Related

I need to get all even numbers from random length 2D Array and make another 2D array with even numbers I've got

My Java code get all numbers I need, but every row in new array have length like in old array. How to make array with different row length only for numbers I've got?
Please check for my code:
import java.util.Arrays;
import java.util.Random;
public class Help {
public static void main(String[] args) {
Random random = new Random();
int n = random.nextInt(10);
int m = random.nextInt(10);
if (n > 0 && m > 0) {
int[][] arr = new int[n][m];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = random.nextInt(20);
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("***** EvenMatrix *****");
int[][] evenMatrix = new int[n][m];
int evenElement = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] % 2 != 0) {
continue;
} else
evenElement = arr[i][j];
for (int k = 0; k < arr[i].length; k++) {
evenMatrix[i][j] = evenElement;
}
System.out.print(evenMatrix[i][j] + " ");
}
System.out.println();
}
System.out.println(Arrays.deepToString(evenMatrix));
} else {
System.out.println("Incorrect array length! Try again!");
System.exit(0);
}
}
}
I wanted to help but didn't understand the question well
Let's say your random numbers are 3x3 for n and m
And let's say your array "arr" is
[1,2,3]
[4,5,6]
[7,8,9}
And you want to be your array "evenMatrix" to be
[2,4,6,8] n = 1 and m = 4
or
[2,4] n = 2 and m = 2
[6,8]
Not n = 3 m = 3 just like in the array "arr"
[2,4,6]
[8,0,0]
is that right? If so you can check n and m before creating the "evenArray" like
int[][] evenMatrix;
if(n<m)
evenMatrix = new int[m][m];
else
evenMatrix = new int[n][n];
creating a square matrix but this still has problems let's say your random numbers are n = 5 and m = 2 so this code will create a 5x5 matrix and fill with even numbers and let's say your randomize arr array doesn't have that many even numbers are so it will become something ugly
The easy solution here is to use an ArrayList, however, we can also create variable length rows using the following, note the comments below explaining the process, but the key is this int[][] evenMatrix = new int[n][];, note how we only specify the column size, not the row size.
Complete code:
System.out.println("***** EvenMatrix *****");
//Create 3D array
int[][] evenMatrix = new int[n][];
for (int i = 0; i < arr.length; i++) {
//Create inner row that we will trim later
int[] evenElements = new int[m];
//Create a counter to track variable locations
int counter = 0;
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] % 2 != 0) {
continue;
} else{
evenElements[counter] = arr[i][j];
//Incriment counter
counter++;
}
System.out.print(arr[i][j] + " ");
}
System.out.println();
//Trim the inner array to the correct length that we know from the `counter`
evenElements = Arrays.copyOf(evenElements, counter);
//Assign the inner row of variable length to the 3D matrix
evenMatrix[i] = evenElements;
}
//Print the result
System.out.println(Arrays.deepToString(evenMatrix));
Example output of the above code:
1 11 15 0 15 18 10
6 12 0 13 15 15 3
10 13 6 1 12 4 12
10 7 12 8 19 4 6
5 10 4 12 4 5 5
***** EvenMatrix *****
0 18 10
6 12 0
10 6 12 4 12
10 12 8 4 6
10 4 12 4
[[0, 18, 10], [6, 12, 0], [10, 6, 12, 4, 12], [10, 12, 8, 4, 6], [10, 4, 12, 4]]

Print the sum of the row in a 2D Array after each row

I'm trying to get the sum of each row printed out after that row. It needs to be formatted like this
2 5 6 3| 16
9 4 4 7| 24
1 10 2 3| 16
8 4 5 3| 20
-----------------
20 23 17 16| 76
Doesn't have to be as nice, but close to it. I have to use a toString method, here is what I have so far.
Edit: Got it solved thanks to #KevinAnderson. Needed to append rowSum[r] to Arrays instead of trying to use another for loop to get the values.
public String toString() {
//Stores the colSum into a string col
String col = "";
for (int j = 0; j < cell[0].length; j++) {
col += " " + colSum[j];
}
//Calculates the total of both the rows and columns
for (int i = 0; i < cell.length; i++) {
for (int j = 0; j < cell[0].length; j++) {
grandTotal += cell[i][j];
}
}
//Prints the array
String array = "";
for (int r = 0; r < cell.length; r++) {
for (int c = 0; c < cell[r].length; c++) {
array += " " + cell[r][c];
}
array += "|" + +rowSum[r] + "\n";
}
return array + "-----------------" + "\n" + col + "| " + grandTotal;
}
rowSum and colSum are calculated in a separate method that can be provided if need be, but they do work as intended.
What I believe I need to do is store the value of rowSum in either an int value and print it, or increment through rowSum in some way. I've tried both, and so far it prints out the whole array that it is stored into.
Here a solution by using two for-loops.
One to print the sum of the rows the other to print the sum of the columns
Also to build the whole sum get track of it either in the first or the second for-loop.
package so;
import java.util.*;
public class RemoveString {
public static void main(String[] args) {
int[][] arr = {{2, 5, 6, 3}, {9, 4, 4, 7}, {1, 10, 2, 3}, {8, 4, 5, 3}};
System.out.println(toString(arr));
}
public static String toString(int[][] cell) {
int sum = 0;
int allSum = 0;
int counter = 0;
String resultString = "";
for (int i = 0; i < cell.length; i++) {
for (int j = 0; j < cell[i].length; j++) {
// Count the columns for the condition later on
if (i == 0) {
counter++;
}
sum += cell[i][j];
resultString += cell[i][j] + " ";
}
resultString += "| " + sum + "\n";
sum = 0;
}
resultString += "--------------\n";
for (int i = 0; i < counter; i++) {
for (int j = 0; j < cell.length; j++) {
sum += cell[j][i];
}
allSum += sum;
resultString += sum + " ";
sum = 0;
}
resultString += "|" + allSum;
return resultString;
}
}
Creates the output
2 5 6 3 | 16
9 4 4 7 | 24
1 10 2 3 | 16
8 4 5 3 | 20
--------------
20 23 17 16 |76
You can first prepare two arrays of sums by rows and columns, then it is easier to print this:
2 5 6 3 | 16
9 4 4 7 | 24
1 10 2 3 | 16
8 4 5 3 | 20
----------------
20 23 17 16 | 76
Code:
// assume that we have a rectangular array
int[][] arr = {
{2, 5, 6, 3},
{9, 4, 4, 7},
{1, 10, 2, 3},
{8, 4, 5, 3}};
// array of sums by rows
int[] sum1 = Arrays.stream(arr)
.mapToInt(row -> Arrays.stream(row).sum())
.toArray();
// array of sums by columns
int[] sum2 = Arrays.stream(arr)
.reduce((row1, row2) -> IntStream
.range(0, row1.length)
.map(i -> row1[i] + row2[i])
.toArray())
.orElse(null);
// output
IntStream.range(0, arr.length)
// iterate over the indices of the rows of an array
.peek(i -> Arrays.stream(arr[i])
// elements of the row
.forEach(e -> System.out.printf("%2d ", e)))
// sum of the row
.peek(i -> System.out.printf("| %2d", sum1[i]))
// end of the row, new line
.forEach(i -> System.out.println());
// line of hyphens, assume that all numbers are two-digit
System.out.println("-" .repeat(arr[0].length * 2 + arr[0].length + 4));
// line of sums by columns
IntStream.range(0, sum2.length)
// sum of column
.forEach(i -> System.out.printf("%2d ", sum2[i]));
// last number, sum of sums, total
System.out.printf("| %2d", Arrays.stream(sum2).sum());
"%2d" - format as a two-digit number.
See also: Pascal's triangle 2d array - formatting printed output

How to sum rows and columns of a 2D array individually with Java?

Here is the problem I'm working on:
Write a program that reads an 3 by 4 matrix and displays the sum of each
column and each row separately.
Here is the sample run:
Enter a 3-by-4 matrix row by row:
1.5 2 3 4
5.5 6 7 8
9.5 1 3 1
Sum of the elements at column 0 is 16.5
Sum of the elements at column 1 is 9.0
Sum of the elements at column 2 is 13.0
Sum of the elements at column 3 is 13.0
Sum of the elements at Row 0 is: 10.5
Sum of the elements at Row 0 is: 26.5
Sum of the elements at Row 0 is: 14.5
and here is the code that I have come up with:
package multidimensionalarrays;
public class MultidimensionalArrays {
public static void main(String[] args) {
double sumOfRow = 0;
double[][] matrix = new double[3][4];
java.util.Scanner input = new java.util.Scanner(System.in); //Scanner
System.out.println("Enter a 3 by 4 matrix row by row: ");
//Prompt user to enter matrix numbers
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
matrix[row][col] = input.nextDouble();
}
}
double[] sumOfCol =new double[matrix[0].length];
for (int i = 0; i < matrix.length; i++) { //row
for (int j = 0; j < matrix[i].length; j++) { //column
sumOfRow += matrix[i][j];
sumOfCol[j] += matrix[i][j];
}
System.out.println("Sum of the elements at row " + row + " is: " + sumOfRow);
}
System.out.println("Sum of the elements at column " + col + " is: " + sumOfCol);
}
}
My problem is that when it gets to the end to print the sums for columns and rows, it is not recognizing the row or col variables. I've been playing with it and switching things around for probably hours now and I just can't seem to get this right, can someone help me with what I'm doing wrong? Also I don't know if I'm doing the column summing correctly?
In your matrix, it is a 3-by-4 matrix from the code segment double[][] matrix = new double[3][4];. The first index is the row index, and the second index is the column index.
Please note that your double[][] matrix is an array of arrays. Namely, matrix is an array of three arrays of length 4, and by convention, each sub-array can be seen as an array of objects arranged in one row. This is called row major order.
For example, in the array
0 1 2 4
0 1 3 9
0 1 5 15
it is really stored as
matrix[0]: [matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3] and so [0 1 2 4]
matrix[1]: [matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3] and so [0 1 3 9]
matrix[2]: [matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3] and so [0 1 5 25]
Here is a simpler algorithm that uses loops to find the sum of values for each row and column value, but requires two passes:
/* After the prompt code segment and sumOfCol in the main method */
// Row (major index)
for (int row = 0; row < matrix.length; row++) {
int rowSum = 0;
for (int col = 0; col < matrix[row].length; col++) {
rowSum += matrix[row][col];
}
System.out.println("Sum of the elements at row " + row + " is: " + rowSum);
}
// Column (minor index)
// Assuming the length of each row is the same
for (int col = 0; col < matrix[0].length; col++) {
int colSum = 0;
for (int row = 0; row < matrix.length; row++) {
colSum += matrix[row][col];
}
System.out.println("Sum of the elements at col " + col + " is: " + colSum);
}
The output is
Enter a 3 by 4 matrix row by row:
0 1 2 4
0 1 3 9
0 1 5 15
Sum of the elements at row 0 is: 7
Sum of the elements at row 1 is: 13
Sum of the elements at row 2 is: 21
Sum of the elements at col 0 is: 0
Sum of the elements at col 1 is: 3
Sum of the elements at col 2 is: 10
Sum of the elements at col 3 is: 28
The variable counting the rows is called i at the point where you print the row sum.
For the column sums you need another loop to print them one by one.

generate specific numbers for row and column in java

i want to write a code that makes a specific numbers in the loop .
for example generate numbers like this :
column 1 - row 1
column 1 - row 2
column 1 - row 3
and then generate this ( for example):
column 2 - row 1
column 2 - row 2
column 2 - row 3
column 2 - row 4
is there any way to write this Algorithm ? thank you so much
code , i have a code like this but i want to manage it :
boolean[][] mapEq = new boolean[mapWidth][mapHeight];
int free = mapWidth * mapHeight;
int randomFree = ((int) (free * Math.random()));
int x = 0, y = 0;
for (int i = 0, k = 0; i < mapWidth; i++) {
for (int j = 0; j < mapHeight; j++) {
if (!mapEq[i][j]) {
if (k == randomFree) {
x = i;
y = j;
break SearchRandom;
} else {
k++;
}
}
}
}
it creat a random thing but i want to make a specific number for example
for column 1 - row 1 and row 2 and row 3
and for column 2 - row 1 and row 2 and row 3 and row 4
Maybe something like this?
int[] columnLengths = {3, 4}; // Lengths of the columns
for(int i = 0; i < columnLengths.length; i++) { // Loop the columns
for(int j = 0; j < columnLengths[j]; j++) { // Loop the rows
System.out.println("column " + i + " - row " + j);
}
}
I am really not sure what you are trying to make, but this is what I understood.

2D array even odd java

I have to segregate the even and odd numbers in a 2D array in java in two different rows (even in row 1 and odd in row two). I have included the output of my code bellow here is what I have:
class TwoDimensionArrays {
public static void main(String[] args) {
int sum = 0;
int row = 2;
int column = 10;
int[][] iArrays = new int[row][column];
for(int rowCount = 0; rowCount < iArrays.length /*&& rowCount % 2 == 0*/; rowCount++) {
for(int columnCount = 0; columnCount < iArrays[0].length /*&& columnCount % 2 != 0*/; columnCount++) {
if(columnCount % 2 != 0 /*&& rowCount % 2 == 0*/) {
iArrays[rowCount][columnCount] = columnCount + 1;
}
}
}
System.out.println("The array has " + iArrays.length + " rows");
System.out.println("The array has " + iArrays[0].length + " columns");
for(int rowCount = 0; rowCount < iArrays.length; rowCount++) {
for(int columnCount = 0; columnCount < iArrays[0].length; columnCount++) {
System.out.print(iArrays[rowCount][columnCount] + " ");
sum += iArrays[rowCount][columnCount];
}
System.out.println();
}
System.out.println("The sum is: " +sum);
}
}
//OUTPUT//
/*The array has 2 rows
The array has 10 columns
0 2 0 4 0 6 0 8 0 10
0 2 0 4 0 6 0 8 0 10
The sum is: 60*/
Can anyone lend a hand?
Thank you in advance.
Instead of passing over the list twice try this:
for(int v = 0; v < 20; v++) {
iArrays[v % 2][(int)v/2] = v;
}
This will set iArrays to:
[[0,2,4,6,8,10,12,14,16,18],
[1,3,5,7,9,11,13,15,17,19]]
What is happening is the row is being set to the remainder of v % 2 (0 if v is even, 1 if v is odd) and the col is being set to the corresponding index (with the cast to int to drop any fraction). You can even generalize it like this:
public static int[][] group(int groups, int size){
int[][] output = new int[groups][size];
for(int value = 0; value < (groups*size); value++) {
output[value % groups][(int)value/groups] = value;
}
return output;
}
Then a call to group(2, 10) will return:
[[0, 2, 4, 6, 8, 10, 12, 14, 16, 18], [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]]
If I understand your question, one solution is to iterate the array from 0 to COLUMN and set each successive slot to two plus the previous slots value (starting with 0 for even and 1 for odd). Like,
public static void main(String arg[]) {
final int ROW = 2;
final int COLUMN = 10;
int[][] iArrays = new int[ROW][COLUMN];
for (int i = 0; i < COLUMN; i++) {
iArrays[0][i] = (i > 0) ? iArrays[0][i - 1] + 2 : 0; // 0,2,4,6...
iArrays[1][i] = (i > 0) ? iArrays[1][i - 1] + 2 : 1; // 1,3,5,7...
}
System.out.println(Arrays.deepToString(iArrays));
}
Output is
[[0, 2, 4, 6, 8, 10, 12, 14, 16, 18], [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]]

Categories