这就是我如何在1到6之间生成一个唯一的no并从drawable文件夹中获取适当的图像.
Random rand = new Random();
// n = the number of images, that start at idx 1
rndInt = rand.nextInt(6) + 1;
String imgName = "card" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
imgView.setImageResource(id);
Run Code Online (Sandbox Code Playgroud)
我想要的是,我必须调用这个方法7次,每次这个方法都应该返回一个唯一的随机编号.所以没有一个已经选定的数字会再次出现.
Dan*_*yer 37
解决此类问题的常用方法是创建一个包含每个可能值的列表并对其进行随机播放(使用Collections.shuffle).然后,每次需要值时,从列表中使用一个项目.这将确保您不会多次使用相同的值,但仍允许随机顺序.
这是一个使用Dan Dyer建议的方法创建随机排列的示例类.它确保每个.next()调用给出一个新的数字,直到构造函数中给出的数字.之后,它会缠绕并再次给出相同的序列.这对于改组播放列表非常有用.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class RandomPermutation{
private List<Integer> list;
private int index;
/**
* Create a random permutation the sequence of numbers 0, 1, ... , n - 1.
* @param n Range specifier, must be positive
*/
public RandomPermutation(int n) {
if (n <= 1) {
throw new IllegalArgumentException(
"Positive number expected, got: " + n);
}
list = new ArrayList<Integer>();
newList(n);
}
/**
* Creates a new list
*/
public void newList(int n) {
index = -1;
list.clear();
for (int i = 0; i < n; i++) {
list.add(i);
}
Collections.shuffle(list);
}
/**
* Retrieve the next integer in sequence.
*/
public int next() {
index = (index + 1) % list.size();
return list.get(index);
}
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句.不要使用Snake使用的方法.这不仅仅是因为一旦使用了所有数字它就会冻结.这可以修复.问题更多的是程序越来越慢,因为listIdontWantAnymore中的数字越来越多.只有6个数字不是问题,但如果范围很大,它可能会导致相当大的减速.考虑在10000个数字之间选择.选择了9900个数字后,有1%的机会击中一个好数字.在9990之后,有0.1%的机会获得一个好的数字等.
以下是如何使用该类的示例:
static RandomPermutation randomPerm = new RandomPermutation(7)
int NextRandomNumber() {
return randomPerm.next() + 1;
}
Run Code Online (Sandbox Code Playgroud)