2013-10-14 29 views
-3

我想創建一個函數,在數組中選取一個隨機數並避免在下次選擇相同的數字。
這是我的代碼(它工作在某個時間,大部分是循環)

請幫助我,謝謝。挑選一個數組中的數字,並避免選擇相同的數字?

private static int pick(int[] x) { 
    int upperbound = x[x.length-1]; 
    int lowerbound = x[0]; 
    int count=0; 
    int ranvalue; 
    int ranindex; 
    Random rand = new Random(); 

    do{ 
     ranindex = rand.nextInt(upperbound-lowerbound) + lowerbound; 
     count++; 
    }while(x[ranindex]==-1||count!=x.length-1); 

    ranvalue=x[ranindex]; 
    x[ranindex]=-1; 

    return ranvalue; 
} 
+0

它看起來對我來說,你的代碼只有真正嘗試選擇一個號碼,它只是不斷重複,只要它是一個無效的數字。 –

+1

如果您只想避免連續兩次選取相同的號碼,您可以跟蹤您以前的號碼。如果你想避免重複選擇,你可以考慮從你的數組(或鏈表)中刪除你的值, –

回答

5

如果你的數組的大小爲n,那麼你最多可以得到n個不同的索引。我建議如下:

  • 創建一個數組從0n-1
  • 隨機播放它。
  • 在每一步,從該數組中取下一個元素,並將其用作源數組的偏移量。

還應包裝這個邏輯到一個類是這樣的:

public class Picker { 

    private int[] source; 

    private List<Integer> offsets; 

    private int currentIndex = 0; 

    public Picker(int[] source) { 
    this.source = source; 

    Integer[] indexes = new Integer[source.length]; 
    for(int i=0;i<source.length;i++) { 
     indexes[i] = i; 
    } 

    this.offsets = Arrays.asList(indexes); 
    Collections.shuffle(this.offsets); 
    } 

    public Integer next() { 
    return source[offsets.get(currentIndex++)]; 
    } 

} 

實施例:

public static void main(String[] args) { 

    int[] source = {8,3,5,9}; 
    Picker picker = new Picker(source); 

    for(int i = 0; i<4;i++) { 
    System.out.println(picker.next()); 
    } 
} 

輸出:

5 
3 
8 
9 

編輯:或者也可以簡單:

Integer[] source = {8,3,5,9}; 

//Copy the source and shuffle it 
List<Integer> dest = Arrays.asList(source); 
Collections.shuffle(dest); 

//Then display 
for (int i = 0;i<source.length;i++) { 
    System.out.println(dest.get(i)); 
} 
相關問題