2014-06-25 28 views
0

我期待完全交換兩個數組的內容,而不是交換數組內的整數,但跨越兩個整數。我對從何處開始感到困惑。交換兩個整數的二維數組

即...

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) { 

} 

} 
+0

第一個問題:當你的演示不是方形時,你的代碼使用方形矩陣。修復。對於交換本身,請使用大小等於您所擁有的行數的臨時數組。然後你可以這樣做:'temp = a; a = b; b = temp;' –

+0

你可以有臨時變量嗎? (這種情況,除非這是一個愚蠢的行爲,在禁止的情況下) –

+0

是的,臨時變量是好的,它實際上比我預期的要簡單得多,我想在一些瘋狂的循環中交換元素,一。感謝您的輸入 – NikoBellic

回答

0

你可以簡單的交換matrix領域:

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

你或許應該首先檢查矩陣具有相同的大小。或者,也可以將ab之間的rows字段的值交換。

+0

我對僞代碼的看法太過分了,並且認爲我需要遍歷並更改每個元素,謝謝。如果他們不匹配,我只使用try/catch並拋出一個錯誤。 – NikoBellic