簡體   English   中英

Java:交換包含最小值和最大值的二維數組行

[英]Java: Swap 2D array rows that contain minimum and maximum values

我在制作 function 時遇到問題,它將交換二維 Arrays 行,其中包括最大值和最小值。

我想不出如何將其變成代碼的方法。 我需要幫助。 我試圖編輯數組中的最小值和最大值的代碼,以給我最大和最小數字的行索引,但我很困惑,我不知道該怎么做。 請幫助我了解如何獲取最大值和最小值的 arrays 行索引,以便我可以將其放入行切換 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);
}
}

存儲具有最小值和最大值的行:

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;
        }
    }
}

然后你可以檢查rowWithMin == rowWithMax 如果沒有,例如像這樣交換兩行:

public static void swapRows(int array[][], int rowA, int rowB) {
   int tmpRow[] = array[rowA];
   array[rowA] = array[rowB];
   array[rowB] = tmpRow;
}

參考: 數組交換 - 二維數組

其他示例: 交換雙二維數組 java 的行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM