我想随机生成一个数组中的数字,每个数字也应该是唯一的,我给出了这段代码。请帮我,请不要建议数组列表,因为我正在为黑莓应用程序构建黑莓API不支持数组列表或集合或哈希集,因此请建议我仅在这段代码中使用数组。
Random rgen = new Random(); // Random number generator
//--- Initialize the array
for (int i=0; i<20; i++) {
quesNum[i] = i;
}
//--- 通过随机交换每个元素来进行洗牌
for (int i=0; i< 20; i++) {
int randomPosition = rgen.nextInt(20);
int temp = quesNum[i];
quesNum[i] = quesNum[randomPosition];
quesNum[randomPosition] = temp;
}
你的代码几乎没问题,但你应该使用修改后的费舍尔-耶茨洗牌 http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle反而:
for (int i=0; i < 20; i++) {
// Partition the array into "shuffled" at the start
// and "unshuffled" at the end. Select a random
// unshuffled one, and swap it with the one at the
// border of shuffled/unshuffled
int randomPosition = i + rgen.nextInt(20 - i);
int temp = quesNum[i];
quesNum[i] = quesNum[randomPosition];
quesNum[randomPosition] = temp;
}
从你的问题中并不清楚你想要什么——验证你的想法是正确的?如果此答案对您没有帮助,请澄清问题(最好不要使用文字缩写)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)