【发布时间】:2012-06-03 16:46:57
【问题描述】:
这是我的家庭作业:
Random r = new Random(); public int get100RandomNumber() { return 1 + r.nextInt(100); }给你一个名为 getrand100() 的预定义函数(上图),它 返回一个整数,它是 1-100 中的一个随机数。你可以打电话 此功能随心所欲,但请注意此功能 是相当资源密集型的。您不能使用任何其他随机 发电机。您不能更改
getrand100()的定义。输出:以随机顺序打印数字 1-20。 (不是 20 个随机数)
我尝试过的..
public class MyClass {
static Random r = new Random();
static HashSet<Integer>;
public static void main(String args[]) {
myMethod();
System.out.println(s);
}
public static void myMethod() {
boolean b = false;
s = new HashSet<Integer>();
int i = getRand100();
if (i >= 20)
i = i % 20;
int j = 0;
int k, l;
while (s.size() <= 20)
{
System.out.println("occurence no" + ++j);
System.out.println("occurence value" + i);
b = s.add(i);
while (!b) {
k = ++i;
if(k<=20)
b = s.add(k);
if(b==true)
break;
if (!b) {
l = --i;
if(i>=1&&i<=20)
b = s.add(l);
if(b==true)
break;
}
}
}
System.out.println(s);
}
public static int getRand100()
{
return r.nextInt(100) + 1;
}
}
感谢您的帮助!
【问题讨论】:
-
你的意思是,如果你得到一个 x == 0 或 x > 20 的数字 x,你必须拒绝它?
-
我认为“以随机顺序打印 1-20 的数字”是指您想要取出所有 1-20 的数字并以随机顺序打印出来,所有可能的顺序均等可能.对吗?
-
如果这个问题这么简单,那我就不在这里问了..
-
删除我的反对票,因为您更新了问题。最好描述一下您使用当前代码获得的结果,以及为什么与您的预期不同。
标签: java algorithm random permutation