如何从集合中随机选取一个元素? 我特别感兴趣的是从a中随机选取一个元素 Java中的HashSet或LinkedHashSet。 也欢迎其他语言的解决方案。
当前回答
你也可以将set转换为数组use array 它可能会在小范围内工作,我看到for循环中投票最多的答案是O(n)
Object[] arr = set.toArray();
int v = (int) arr[rnd.nextInt(arr.length)];
其他回答
不如就
public static <A> A getRandomElement(Collection<A> c, Random r) {
return new ArrayList<A>(c).get(r.nextInt(c.size()));
}
Icon有一个集合类型和一个随机元素操作符,一元“?”,因此表达式
? set( [1, 2, 3, 4, 5] )
将产生1到5之间的随机数。
当程序运行时,随机种子被初始化为0,因此要在每次运行时产生不同的结果,请使用randomize()
你知道吗?
在java.util.Collections中有一些有用的方法用于洗牌整个集合:collections .shuffle(List<?>)和collections .shuffle(List<?>列表,随机rnd)。
在c#中
Random random = new Random((int)DateTime.Now.Ticks);
OrderedDictionary od = new OrderedDictionary();
od.Add("abc", 1);
od.Add("def", 2);
od.Add("ghi", 3);
od.Add("jkl", 4);
int randomIndex = random.Next(od.Count);
Console.WriteLine(od[randomIndex]);
// Can access via index or key value:
Console.WriteLine(od[1]);
Console.WriteLine(od["def"]);
如果你真的只想从Set中选择“任意”对象,而不保证随机性,最简单的方法是使用迭代器返回的第一个对象。
Set<Integer> s = ...
Iterator<Integer> it = s.iterator();
if(it.hasNext()){
Integer i = it.next();
// i is a "random" object from set
}
推荐文章
- 如何格式化Joda-Time DateTime仅为mm/dd/yyyy?
- 使嵌套JavaScript对象平放/不平放的最快方法
- 使用该集合的原因。种子功能
- 如何在POM.xml中引用环境变量?
- 大的Ө符号到底代表什么?
- 如何在android中复制一个文件?
- 将整数转换为字符串,以逗号表示千
- 堆与二叉搜索树(BST)
- 接口方法的最终参数-有什么意义?
- Java中的@UniqueConstraint注释
- 给定一个数字数组,返回所有其他数字的乘积的数组(不除法)
- 如何在清洁模式下运行eclipse ?如果我们这样做会发生什么?
- 关于数据库,每个开发人员应该知道些什么?
- 获取java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory异常
- 广度优先Vs深度优先