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 rowWithMin = i;
int rowWithMax = i;
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;
}
}
if (rowWithMin != rowWithMax){
swapRows(arr, rowWithMin, rowWithMax);}
}
print2Dmas(arr);
}
}
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 swapRows(int array[][], int rowA, int rowB) {
int tmpRow[] = array[rowA];
array[rowA] = array[rowB];
array[rowB] = tmpRow;
}
}