I'm having problems making a function that would swap a 2Dimensional Arrays rows, that include the biggest and the smallest values.
I cant think of a way how to make it into a code. I need a helping hand. I tried to edit the code of min and max value in an array to give me the row index of the biggest and smallest numbers but i got confused and im not sure how to do it. Pls help me on how to get the arrays row index of the max and min values so I can put it into the row switching function.
ANSWER EXAMPLE:
if the array was like this:
5 2 1 8
15 -4 5 18
7 3 44 9
12 1 18 76
it would swap it like this:
5 2 1 8
12 1 18 76
7 3 44 9
15 -4 5 18
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
{
final int kolonna = (int) (Math.random()*(9-1+1)+1);
final int rinda = (int) (Math.random()*(9-1+1)+1);
int [][] arr = new int [kolonna][rinda];
//fill the grid
for (int rin = 0; rin < arr.length; rin++) {
for (int kol = 0; kol < arr[rin].length; kol++) {
arr[rin][kol] = (int) (Math.random() * 201) - 100;
}
}
print2Dmas(arr);
System.out.println();
int mazs=0;
int liels=0;
for (int i = 0; i < arr.length; i++) {
int minInRow = arr[i][0];
int maxInRow = arr[i][0];
for (int j = 0; j < arr[i].length; j++) {
if (minInRow > arr[i][j]) {
minInRow = arr[i][j];
mazs = j;
}
if (maxInRow < arr[i][j]) {
maxInRow = arr[i][j];
liels = j;
}
}}
exchangeAnyTwoRows(arr,mazs,liels);
}
}
public static void print2Dmas(int mas[][]) {
for(int i = 0; i < mas.length; i++) {
for(int j = 0; j < mas[i].length; j++) {
System.out.print(mas[i][j] + " ");
//System.out.println();
}
System.out.println();
}
}
public static void exchangeAnyTwoRows(int[][] matrix,int K, int L){
for (int i = 0; i < matrix[0].length; i++) {
int temp = matrix[K - 1][i];
matrix[K - 1][i] = matrix[L - 1][i];
matrix[L - 1][i] = temp;
}
print2Dmas(matrix);
}
}
Store the row with the min and max value:
for (int i = 0; i < arr.length; i++) {
int rowWithMin = arr[i][0];
int rowWithMax = arr[i][0];
for (int j = 0; j < arr[i].length; j++) {
if (rowWithMin > arr[i][j]) {
rowWithMin = i;
mazs = j;
}
if (rowWithMax < arr[i][j]) {
rowWithMax = i;
liels = j;
}
}
}
Then you can check if rowWithMin == rowWithMax
. If not, swap the two rows for example like this:
public static void swapRows(int array[][], int rowA, int rowB) {
int tmpRow[] = array[rowA];
array[rowA] = array[rowB];
array[rowB] = tmpRow;
}
Reference: Array swap - 2d array
Other example: Swapping rows of double 2d array java
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.