数组改组不起作用
我正在尝试编写代码来在不使用集合的情况下对数组进行洗牌。
我的洗牌代码
是
private double amounts[] = { 0, 0.01, 1000000, 25, 250000, 75, 50, 1000,
200, 100, 400000, 750, 5000, 750000, 500, 100000, 300, 75000, 800,
20, 300000, 10, 50, 750, 25, 5, 1 };
public void Shuffle(){
Random rgen = new Random();
for (int i=0; i > amounts.length; i++) {
int randomPosition = rgen.nextInt(amounts.length);
double temp = amounts[i];
amounts[i] = amounts[randomPosition];
amounts[randomPosition] = temp;
}
}
启动它的代码
public void casesSetup() {
for (int i = 0; i < briefcase.length; i++) {
if (i == 0) {
} else {
briefcase[i] = new Briefcase();
double value = amounts[i];
briefcase[i].setAmount(value);
briefcase[i].setFace(i);
}
}
}
我的问题是它们没有被随机化有人知道为什么吗?
I am trying to write code to shuffle an Array without using Collections.
My shuffle code
the Amounts
private double amounts[] = { 0, 0.01, 1000000, 25, 250000, 75, 50, 1000,
200, 100, 400000, 750, 5000, 750000, 500, 100000, 300, 75000, 800,
20, 300000, 10, 50, 750, 25, 5, 1 };
public void Shuffle(){
Random rgen = new Random();
for (int i=0; i > amounts.length; i++) {
int randomPosition = rgen.nextInt(amounts.length);
double temp = amounts[i];
amounts[i] = amounts[randomPosition];
amounts[randomPosition] = temp;
}
}
the code that initiates it
public void casesSetup() {
for (int i = 0; i < briefcase.length; i++) {
if (i == 0) {
} else {
briefcase[i] = new Briefcase();
double value = amounts[i];
briefcase[i].setAmount(value);
briefcase[i].setFace(i);
}
}
}
my problem here is that they are not being randomized anyone has an idea why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
第一个片段中的 for 循环似乎是错误的,
不是吗?
for loop in your first snippet seem to be wrong
shouldn't it be
将值存储在列表中并使用
Collections.shuffle http: //download.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List)
自己手动滚动似乎没有必要
Store the values in a List and use
Collections.shuffle http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List)
Hand rolling this on your own seems unnecesary
我的建议是开始反向洗牌:
假设 Random.nextInt(N) 的分布在 0..N-1 上是均匀的,这将对数组进行洗牌,每个排列的可能性均等。对此的论证是直截了当的。
My tip is to start shuffling in reverse:
Assuming that the distribution of Random.nextInt(N) is uniform on 0..N-1 this will shuffle your array with each permutation being equally as likely. The argumentation for that is straight forward.
除了 for 循环错误之外,您还应该更改
为
以获得均匀的随机分布。
In addition to your for loop being wrong, you should change
to
to get a uniform random distribution.