簡體   English   中英

交換兩個2D整數數組

[英]Swapping two 2D Arrays of integers

我希望完全交換兩個數組的內容,而不是交換數組內的整數,而是跨兩個數組。 我對從哪里開始感到非常困惑。

即...

Matrix a = 1 2 3   Matrix b = 3 2 1
           4 5 6              6 5 4 

我希望它輸出為

Matrix a = 3 2 1   Matrix b = 1 2 3
           6 5 4              4 5 6 

如果這樣的話。 抱歉! 我的代碼在下面創建數組並用Random填充的開始部分中,我沒有包括測試器,因為我只是輸入要用於計算的數組,而我還沒有准備好這樣做。

import java.util.Random;

public class Matrix {
private int[][] matrix;
private int rows;

//constructors
public Matrix() {
    matrix = new int[3][3];
    rows = 3;
}

public Matrix(int size) {
    matrix = new int[size][size];
    rows = size;
}

//Mutators
public void fill() {
    Random r = new Random();

    for (int i = 0; i < this.rows; i++) {
        for (int j = 0; j < this.rows; j++) {
            this.matrix[i][j] = r.nextInt();
        }
    }
}

public void clear() {
    for (int i = 0; i < this.rows; i++) {
        for (int j = 0; j < this.rows; j++) {
            this.matrix[i][j] = 0;
        }
    }
}

public static void swap(Matrix a, Matrix B) {

}

}

您可以簡單地交換matrix字段:

public static void swap(Matrix a, Matrix b) {
    int[][] tmp = a.matrix;
    a.matrix = b.matrix;
    b.matrix = tmp;
}

您可能應該首先檢查矩陣的大小是否相同。 另外,也可以在ab之間交換rows字段的值。

暫無
暫無

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

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