如何从集合中随机选取一个元素? 我特别感兴趣的是从a中随机选取一个元素 Java中的HashSet或LinkedHashSet。 也欢迎其他语言的解决方案。


当前回答

Icon有一个集合类型和一个随机元素操作符,一元“?”,因此表达式

? set( [1, 2, 3, 4, 5] )

将产生1到5之间的随机数。

当程序运行时,随机种子被初始化为0,因此要在每次运行时产生不同的结果,请使用randomize()

其他回答

你知道吗?

在java.util.Collections中有一些有用的方法用于洗牌整个集合:collections .shuffle(List<?>)和collections .shuffle(List<?>列表,随机rnd)。

你也可以将set转换为数组use array 它可能会在小范围内工作,我看到for循环中投票最多的答案是O(n)

Object[] arr = set.toArray();

int v = (int) arr[rnd.nextInt(arr.length)];
List asList = new ArrayList(mySet);
Collections.shuffle(asList);
return asList.get(0);

不如就

public static <A> A getRandomElement(Collection<A> c, Random r) {
  return new ArrayList<A>(c).get(r.nextInt(c.size()));
}

Clojure的解决方案:

(defn pick-random [set] (let [sq (seq set)] (nth sq (rand-int (count sq)))))