Java 从集合中随机选取一个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/124671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Picking a random element from a set
提问by Clue Less
How do I pick a random element from a set? I'm particularly interested in picking a random element from a HashSet or a LinkedHashSet, in Java. Solutions for other languages are also welcome.
如何从集合中随机选择一个元素?我对从 Java 中的 HashSet 或 LinkedHashSet 中选择一个随机元素特别感兴趣。也欢迎其他语言的解决方案。
采纳答案by Khoth
int size = myHashSet.size();
int item = new Random().nextInt(size); // In real life, the Random object should be rather more shared than this
int i = 0;
for(Object obj : myhashSet)
{
if (i == item)
return obj;
i++;
}
回答by Swaroop C H
Since you said "Solutions for other languages are also welcome", here's the version for Python:
既然你说“也欢迎其他语言的解决方案”,这里是 Python 的版本:
>>> import random
>>> random.choice([1,2,3,4,5,6])
3
>>> random.choice([1,2,3,4,5,6])
4
回答by Jorge Ferreira
In Java:
在 Java 中:
Set<Integer> set = new LinkedHashSet<Integer>(3);
set.add(1);
set.add(2);
set.add(3);
Random rand = new Random(System.currentTimeMillis());
int[] setArray = (int[]) set.toArray();
for (int i = 0; i < 10; ++i) {
System.out.println(setArray[rand.nextInt(set.size())]);
}
回答by matt lohkamp
Can't you just get the size/length of the set/array, generate a random number between 0 and the size/length, then call the element whose index matches that number? HashSet has a .size() method, I'm pretty sure.
你不能只获取集合/数组的大小/长度,生成一个介于 0 和大小/长度之间的随机数,然后调用索引与该数字匹配的元素吗?HashSet 有一个 .size() 方法,我很确定。
In psuedocode -
在伪代码中 -
function randFromSet(target){
var targetLength:uint = target.length()
var randomIndex:uint = random(0,targetLength);
return target[randomIndex];
}
回答by dirtside
PHP, assuming "set" is an array:
PHP,假设“set”是一个数组:
$foo = array("alpha", "bravo", "charlie");
$index = array_rand($foo);
$val = $foo[$index];
The Mersenne Twister functions are better but there's no MT equivalent of array_rand in PHP.
Mersenne Twister 函数更好,但 PHP 中没有与 array_rand 等效的 MT。
回答by da5id
PHP, using MT:
PHP,使用 MT:
$items_array = array("alpha", "bravo", "charlie");
$last_pos = count($items_array) - 1;
$random_pos = mt_rand(0, $last_pos);
$random_item = $items_array[$random_pos];
回答by Mathew Byrne
Javascript solution ;)
Javascript 解决方案 ;)
function choose (set) {
return set[Math.floor(Math.random() * set.length)];
}
var set = [1, 2, 3, 4], rand = choose (set);
Or alternatively:
或者:
Array.prototype.choose = function () {
return this[Math.floor(Math.random() * this.length)];
};
[1, 2, 3, 4].choose();
回答by chickeninabiscuit
A somewhat related Did You Know:
一个有点相关的你知道吗:
There are useful methods in java.util.Collections
for shuffling whole collections: Collections.shuffle(List<?>)
and Collections.shuffle(List<?> list, Random rnd)
.
有一些有用的方法可以java.util.Collections
对整个集合进行混洗:Collections.shuffle(List<?>)
和Collections.shuffle(List<?> list, Random rnd)
.
回答by J.J.
Perl 5
Perl 5
@hash_keys = (keys %hash);
$rand = int(rand(@hash_keys));
print $hash{$hash_keys[$rand]};
Here is one way to do it.
这是一种方法。
回答by Hugh Allen
Iconhas a set type and a random-element operator, unary "?", so the expression
Icon有一个集合类型和一个随机元素运算符,一元“?”,所以表达式
? set( [1, 2, 3, 4, 5] )
will produce a random number between 1 and 5.
将产生一个 1 到 5 之间的随机数。
The random seed is initialized to 0 when a program is run, so to produce different results on each run use randomize()
当程序运行时,随机种子被初始化为 0,因此每次运行都会产生不同的结果,请使用 randomize()