开发者

How to generate n random numbers from a list of m numbers in java?

开发者 https://www.devze.com 2023-02-14 03:43 出处:网络
For example I have a list of 20 numbers and i try to rand开发者_开发问答om generate six of them without repeating them. Any ideas?If you have a java.util.List you could simple shuffle it and pick the

For example I have a list of 20 numbers and i try to rand开发者_开发问答om generate six of them without repeating them. Any ideas?


If you have a java.util.List you could simple shuffle it and pick the first six.


An easy way is to randomly shuffle the list and then take the first six elements:

List<Number> population = ...your list of 20 numbers...
Collections.shuffle(population);
List<Number> sample = population.subList(0, 6);
0

精彩评论

暂无评论...
验证码 换一张
取 消