2014-09-25 77 views
1

用戶將在號碼爲(變體)型,則對於Ĵ(元件對於每個變體)的數量,最後的最大值可能(maxElem)。 使用輸入值,任務是生成非重複的隨機數(在變體中不重複,意思是我,但數字可能會在整個陣列中重複)。產生非重複數的隨機二維陣列,爪哇

例如,一個成功的輸出給所述輸入3(I),5(j)中,圖9(maxElem),將是:

| 8 | 1 | 7 | 9

3 | 8 | 2 | | 5

2 | 6 |您可能會注意到,數字4在整個數組中重複3次(允許)。但是,對於i = 0,編號4是唯一的。

請,引導我這將是改變這一代碼:

靜態掃描儀SC =新的掃描儀(System.in);

static int maxElem;

public static void main(String[] args) { 

    int[][] greatLoto; 

    System.out.println("Of how many variants will the ticket consist? "); 
    int variants = sc.nextInt(); 

    System.out.println("Of how many elements will the variants consist? "); 
    int elements = sc.nextInt(); 

    System.out.println("Which value should be considered the maximum value? "); 
    maxElem = sc.nextInt() + 1; 

    greatLoto = new int[variants][elements]; 

    System.out.println("Initial values: "); 
    show(greatLoto); 

    System.out.println("Modifying values..."); 
    modified(greatLoto); 

    System.out.println("Newest values: "); 
    show(greatLoto); 

} 

private static void show(int[][] greatLoto) { 
    for (int i = 0; i < greatLoto.length; i++) { 
     for (int j = 0; j < greatLoto[i].length; j++) { 
      System.out.print("|" + greatLoto[i][j] + "|"); 
     } 
     System.out.println(""); 
    } 
    System.out.println(""); 
} 

private static void modified(int[][] greatLoto) { 
Random r = new Random(System.currentTimeMillis()); 
    for (int i = 0; i < greatLoto.length; i++) { 
     for (int j = 0; j < greatLoto[i].length; j++) { 

      while (Arrays.asList(greatLoto[i]).contains(r)) { 
       r = new Random(System.currentTimeMillis()); 
      } 
      greatLoto[i][j] = r.nextInt(maxElem);; 

     } 
     System.out.println(""); 

    } 

} 

回答

3

這是更多的評論,但太長:不要使用random.next(),因爲它強制你檢查唯一性。相反,填充列表與有效值和將它洗:

List<Integer> values = new ArrayList<>(); 
for (int i = 1; i <= max; i++) values.add(i); 
Collections.shuffle(values); 

然後,你可以簡單地遍歷值,並採取第j第一號。

請注意,如果j顯着大於我使用隨機方法可能會更有效。

+0

你應該提到,只有當max很小時,這纔是合理的。 – necromancer 2014-09-25 08:41:41

+0

@necromancer確實很好。 – assylias 2014-09-25 08:42:57

+1

它必須是'i <= max;',因爲OP希望包含'maxElem' ... – Robert 2014-09-25 08:45:17

0

需要三個循環:

Loop_1:構建尺寸j的數組,並使用Loop_1B該陣列的各個領域。

Loop_1B:生成具有r.nextInt(maxElem)+1;一個int(它必須是+1因爲nextInt()被覆蓋0包含性和指定值排他地)。之後檢查數組是否已被使用,如果是,則再次運行此循環。

Loop_2:重複Loop_1 i次。

0

最起碼的變化是:

private static void modified(int[][] greatLoto) { 
Random r = new Random(System.currentTimeMillis()); 
    for (int i = 0; i < greatLoto.length; i++) { 
     for (int j = 0; j < greatLoto[i].length; j++) { 
      do { 
       greatLoto[i][j] = r.nextInt(maxElem); 
      } while (Arrays.asList(greatLoto[i]).contains(greatLoto[i][j]));  
     } 
     System.out.println(""); 
    } 

} 

但也有更優雅(但很難代碼)的方式來生成唯一的隨機數不丟棄重複。

+0

它必須是'r.nextInt(maxElem)+1;'因爲OP想要'maxElem'包括... – Robert 2014-09-25 08:44:12