我知道如何使用java Random class随机数.
这将随机出现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);
}
}
Run Code Online (Sandbox Code Playgroud)
题
- 我想在0-13之间随机输入13次
- 如果第一个随机数是例如(5),那么我的第二个随机数将从0-13中随机任意一个数字,排除5 ;
如果第二个随机数是例如(4),那么我的第三个随机数将从0-13中随机任意一个,排除5和4 ; 等等.有没有办法做到这一点?
Boh*_*ian 12
做这个:
List13的大小在代码中:
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
Run Code Online (Sandbox Code Playgroud)
问题 - 我想在0-13之间随机抽取13次
我将开始与List和Collections.shuffle(List)和Random喜欢的东西-
Random rand = new Random();
List<Integer> al = new ArrayList<>();
for (int i = 0; i < 14; i++) {
al.add(i);
}
Collections.shuffle(al, rand);
System.out.println(al);
Run Code Online (Sandbox Code Playgroud)
或者,如果使用Java 8+,则IntStream.range(int, int)生成List.你可以使用a forEachOrdered来显示(在任何一个版本中,你冷使用Collections.shuffle带有隐式随机的)就像
List<Integer> al = IntStream.range(0, 13).boxed().collect(Collectors.toList());
Collections.shuffle(al);
al.stream().forEachOrdered(System.out::println);
Run Code Online (Sandbox Code Playgroud)
我填写一个列表,随机播放,然后迭代它,每次保证一个不同的数字:
public static void main(String[] args) {
int ctr = 13;
List<Integer> list = new ArrayList<>(ctr);
for (int i = 0; i < ctr; ++i) {
list.add(i);
}
Collections.shuffle(list);
for (int i = 0; i < ctr; ++i) {
System.out.println(ctr + ": " + list.get(i));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
193 次 |
| 最近记录: |