在我的(Java Android)游戏中,我在随机位置产生硬币。
硬币可以在屏幕上水平显示6个位置之一(每个水平线最多2个)。
我所做的是为第一枚硬币创建0到5之间的随机数,然后我想生成另一个随机数,不包括第一枚硬币的位置。
因此,例如,硬币1在0到5之间的随机位置产生 - 所以让我们说4。
然后下一枚硬币需要能够在0-3或5之间选择。(基本上0-5除了4)。
我已经设法做到了,但它不是很优雅,我确信必须有一个更好/更清洁的方法来实现这一点,但是,它逃脱了我。
下面代码中的random(int number)方法只返回一个从0到数字1的随机int(使用nextInt),randomBool()只返回一个随机布尔值
另外,请记住,我不想使用任何技术来保持重新生成一个随机数,如果它产生的那个等于我们试图避免的那个。
码
//Return a random number between 0 and 5 excluding the specified number
private int getRandomExcluding(int excludedNumber){
//If previous position was 0 then generate a number between 1 and 5
if (excludedNumber==0){
return random(5)+1;
}
//If position was 5, then generate and return number from 0-4
else if (excludedNumber==5){
return random(5);
}
//If number isn't 0 or 5 (then it is in range of 1-4 use a random bool to determine
// if we are going to get a number less than or greater than the number we are excluding
//True - get number lower than excluded number
else if(randomBool()){
//Excluded number is 1
if (excludedNumber==1){
return 0; //Only posibility
}
//Excluded number is > 1
else {
//Return a random number between 0 (inclusive) and the excluded number (exclusive)
return random(excludedNumber);
}
//False - get number higher than the excluded number (between exludedNumber+1 (inclusive) and 6(exlusive))
else {
return random(6-(excludedNumber+1))+(excludedNumber+1);
}
}
答案 0 :(得分:6)
您可以填充列表并将其随机播放:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Collections.shuffle(numbers);
int coin1 = numbers.get(0);
int coin2 = numbers.get(1);
答案 1 :(得分:1)
试试这个解决方案:
private int getRandomExcluding(int excludedNumber){
int num = random(5);
return num >= excludedNumber ? num+1 : num;
}
它只是生成0到4之间的随机数,如果它大于或等于排除的数字,则会添加一个。这样,所有五个可能的数字均匀分布(如果您的RNG产生均匀分布的数字)。
答案 2 :(得分:0)
解决方案:(如果您喜欢这种类型的输入,可以将 List<Integer> excludes
更改为 int... excludes
)
/**
* Get a random number between a range and exclude some numbers
*
* @param start start number
* @param end end number
* @param excludes list of numbers to be excluded
* @return value between {@code start} (inclusive) and {@code end} (inclusive)
*/
private int getRandomWithExclusion(int start, int end, List<Integer> excludes) {
Collections.sort(excludes); // this method only works with sorted excludes
int random = start + new Random().nextInt(end - start + 1 - excludes.size());
for (int exclude : excludes) {
if (random < exclude) {
break;
}
random++;
}
return random;
}