【发布时间】:2017-01-12 12:07:44
【问题描述】:
我做了一个小的java程序。一个整数将作为输入,然后随机数将打印到控制台,直到我们找到该整数输入。 该代码会有点作弊,因为它会知道输入数字有多少位。
将使用随机数,我想要做的是排除每个已使用的随机数。但我不知道怎么做。好吧,我有一个想法,但这将是一种我不喜欢的廉价旁路。它将从 0 开始,并始终将其增加 1 值,直到我们找到输入。
这(不包括使用的随机数)可以在 java 中完成吗?
我想我们可以列出一个列表,这样每个使用过的数字都会在该列表中。在每个循环中访问列表以检查 number 是否未使用。但这只是想象,在java中真的可以吗?
import java.util.Scanner;
import java.util.Random;
public class Backtracker{
public static void main(String[]args){
int counter = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter integer here: ");
int x = input.nextInt();
Random rand = new Random();
int a = rand.nextInt(100)+0;
int b = rand.nextInt(1000)+100;
int c = rand.nextInt(10000)+1000;
int d = rand.nextInt(100000)+10000;
int e = rand.nextInt(1000000)+10000;
int f = rand.nextInt(10000000)+1000000;
int g = rand.nextInt(100000000)+10000000;
if(x<=100){
while(x != a){
a = rand.nextInt(100)+0;
System.out.println(a);
counter++;
}
System.out.println("Tries: "+counter);
}
else if(x<=1000){
while(x != b){
b = rand.nextInt(1000)+100;
System.out.println(b);
counter++;
}
System.out.println("Tries: "+counter);
}
else if(x<=10000){
while(x != c){
c = rand.nextInt(10000)+1000;
System.out.println(c);
counter++;
}
System.out.println("Tries: "+counter);
}
else if(x<=100000){
while(x != d){
d = rand.nextInt(100000)+10000;
System.out.println(d);
counter++;
}
System.out.println("Tries: "+counter);
}
else if(x<=1000000){
while(x != e){
e = rand.nextInt(1000000)+100000;
System.out.println(e);
counter++;
}
System.out.println("Tries: "+counter);
}
else if(x<=10000000){
while(x != f){
f = rand.nextInt(10000000)+1000000;
System.out.println(f);
counter++;
}
System.out.println("Tries: "+counter);
}
else if(x<=100000000){
while(x != g){
g = rand.nextInt(100000000)+10000000;
System.out.println(g);
counter++;
}
System.out.println("Tries: "+counter);
}
}
}
【问题讨论】:
-
您必须以某种方式保存状态 - 例如您已经使用过的数字。只需创建一个
Set<Integer>并将您的号码保存在那里。 -
将 x 与某种数字进行比较,这真的很像作弊,整数有一个范围,立即使用该范围,而不是使用 else if 大小写。