2014-01-25 76 views
0

好吧,我誤解了這個問題。讀了幾次後,我發現randInt實際上是我用來填充數組的方法。所以當它說打電話randInt它的某種遞歸電話我想。這是它應該看起來像什麼:交換數組中的引用

static int[] randInt(int i, int j) { 
    int[] temp = new int[(j - i) + 1]; 
    for (i = 0; i < j; i++) { 
     temp[i] = i + 1; // here i populate the array 
    } 
    System.out.println(Arrays.toString(temp)); // this prints [1, 2, 3, 4, 5] 
    for (i = 1; i < j;i++){ 
     swapReferences(temp[i], temp[randInt(0,i)]); //this is some sort of recursive call that swaps the references 
     // btw that statement does not compile, how can i pass a method as a parameter? 



    } 
    return temp; 
} 

static void swapReferences(int a, int b) { //these parameters are wrong, need to be changed 
    //Method to swap references 

} 

對不起,我認爲這是如何應該是正確的。

+0

@SotiriosDelimanolis不是它的一個不同的問題。 – user1404664

+3

你會這麼想,但你會錯的。 –

+0

不同_scenario_,同樣的問題。 – csmckelvey

回答

2

Java是按值傳遞的,所以重新分配參數就像你試圖做的那樣是行不通的。

你需要做的是在陣列本身和兩個整數索引作爲參數:

int randInt = generate.nextInt(j-i) + 1; //this is gonna generate a # within the range of the array (so if array is size 5, generates something 1-5) 
for (i = 1; i < j;i++){ 
     swapReferences(temp, i, randInt); //and this is my attempt at swapping the references 
     randInt = generate.nextInt(i) + 1 ; 
    } 

    static void swapReferences(int[] array, int a, int b){ 
    int x = array[a]; 
    array[a] = array[b]; 
    array[b] = x; 

} 

可以發生變異的參數,如傳遞給方法,因爲這裏正在做陣列,但你不能自己重新分配參數。

+0

啊你比我更快,更簡潔+1! – mdewitt

+0

這可以正常工作,但由於某種原因,本書要求我以另一種方式實現它。我編輯了原始帖子,以便您可以確切地查看要查詢的內容。 – user1404664

+1

這不一定是你的書的情況,但我記得當我在大學時,我上課的書中的一些代碼只是沒有寫作而已。我記得有一本書很清楚從C語言翻譯成Java,但很差。沒有一點操縱,許多方法都無法正常工作。 – mdewitt

2

您只是更改a和b所指向的整數,而不是數組指向的標記。你需要改變你的swapReferences方法使陣列作爲輸入,有點像indicies交換

static void swapReferences(int[] arr, int indexA, int index B){ 
    int x = arr[indexA]; 
    a = arr[indexB]; 
    b = x; 
    arr[indexA] = a; 
    arr[indexB] = b; 
} 

static void swapReferences(int[] arr, int indexA, int indexB){ 
    int x = arr[indexA]; 
    arr[indexA] = arr[indexB]; 
    arr[indexB] = x; 
}