用戶將在號碼爲我(變體)型,則對於Ĵ(元件對於每個變體)的數量,最後的最大值可能(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("");
}
}
你應該提到,只有當max很小時,這纔是合理的。 – necromancer 2014-09-25 08:41:41
@necromancer確實很好。 – assylias 2014-09-25 08:42:57
它必須是'i <= max;',因爲OP希望包含'maxElem' ... – Robert 2014-09-25 08:45:17