[英]Generate a random two-dimensional array of non-repeating numbers, Java
用户将输入i (变量)的数字,然后输入j的数字(每个变量的元素),最后输入可能的最大值(maxElem)。 使用输入的值,任务是生成非重复的随机数( 在变量中不重复,对于i意味着 ,但数字可能在整个数组期间重复)。
例如,给出输入3(i),5(j),9(maxElem)的成功输出将是:
4 | 8 | 1 | 7 | 9
3 | 8 | 2 | 4 | 5
2 | 6 | 4 | 8 | 5
您可能会注意到,数字4在整个阵列中重复3次(允许)。 但是,对于i = 0 ,数字4是唯一的。
请指导我对此代码的更改:
static Scanner sc = new Scanner(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("");
}
}
这更像是一个注释但是太长了:不要使用random.next()因为它会强制你检查唯一性。 而是使用有效值填充列表并将其随机化:
List<Integer> values = new ArrayList<> ();
for (int i = 1; i <= max; i++) values.add(i);
Collections.shuffle(values);
然后,您可以简单地迭代值并获取j个第一个数字。
请注意,如果j显着大于i,使用随机方法可能会更有效。
你需要三个循环:
Loop_1:构建一个大小为j
的数组,并对该数组的每个字段使用Loop_1B。
Loop_1B:使用r.nextInt(maxElem)+1;
生成一个int r.nextInt(maxElem)+1;
(它必须是+1
因为nextInt()
覆盖0包含和指定的值)。 然后检查数字是否已在数组中使用,如果是,则再次运行此循环。
Loop_2:重复Loop_1 i
倍。
最小的变化是:
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("");
}
}
但是有更优雅(但难以编码)的方法来生成唯一的随机数而不丢弃重复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.