我知道如何使用 java Random 类随机数。
这将随机一个 0-13 之间的数字 13 次;
public static void main(String[] args) {
int ctr = 13;
int randomNum = 0;
while(ctr != 0) {
Random r = new Random();
randomNum = r.nextInt(13);
ctr--;
System.out.println(ctr +": " + randomNum);
}
}
问题
-我想随机取一个0-13之间的数字13次
-如果第一个随机数是例如(5),那么我的第二个随机数将再次随机生成 0-13 中的任何数字EXCLUDING 5;
如果第二个随机数是例如(4),那么我的第三个随机数将再次随机从 0-13 中的任何数字EXCLUDING 5 和 4; ETC.. 有办法吗?
最佳答案
这样做:
- 创建一个大小为 13 的
List
- 填入数字 0-12
- 使用 JDK Collections 实用方法打乱列表
- 使用打乱顺序的数字(通过遍历列表)
在代码中:
List<Integer> nums = new ArrayList<Integer>();
for (int i = 0; i < 13; i++)
nums.add(i);
Collections.shuffle(nums);
for (int randomNum : nums)
System.out.println(randomNum); // use the random numbers
关于java - 不要随机数之前是随机的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25101871/