如何从集合中随机选取一个元素? 我特别感兴趣的是从a中随机选取一个元素 Java中的HashSet或LinkedHashSet。 也欢迎其他语言的解决方案。
当前回答
在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"]);
其他回答
这与接受的答案(Khoth)相同,但删除了不必要的size和i变量。
int random = new Random().nextInt(myhashSet.size());
for(Object obj : myhashSet) {
if (random-- == 0) {
return obj;
}
}
尽管去掉了前面提到的两个变量,但上面的解决方案仍然是随机的,因为我们依赖于随机(从随机选择的索引开始)在每次迭代中将自己递减到0。
c++。这应该是相当快的,因为它不需要遍历整个集合,也不需要对它排序。这应该适用于大多数现代编译器,假设它们支持tr1。如果没有,您可能需要使用Boost。
Boost文档有助于解释这一点,即使你不使用Boost。
诀窍在于利用数据已被划分为多个bucket的事实,并快速识别随机选择的bucket(具有适当的概率)。
//#include <boost/unordered_set.hpp>
//using namespace boost;
#include <tr1/unordered_set>
using namespace std::tr1;
#include <iostream>
#include <stdlib.h>
#include <assert.h>
using namespace std;
int main() {
unordered_set<int> u;
u.max_load_factor(40);
for (int i=0; i<40; i++) {
u.insert(i);
cout << ' ' << i;
}
cout << endl;
cout << "Number of buckets: " << u.bucket_count() << endl;
for(size_t b=0; b<u.bucket_count(); b++)
cout << "Bucket " << b << " has " << u.bucket_size(b) << " elements. " << endl;
for(size_t i=0; i<20; i++) {
size_t x = rand() % u.size();
cout << "we'll quickly get the " << x << "th item in the unordered set. ";
size_t b;
for(b=0; b<u.bucket_count(); b++) {
if(x < u.bucket_size(b)) {
break;
} else
x -= u.bucket_size(b);
}
cout << "it'll be in the " << b << "th bucket at offset " << x << ". ";
unordered_set<int>::const_local_iterator l = u.begin(b);
while(x>0) {
l++;
assert(l!=u.end(b));
x--;
}
cout << "random item is " << *l << ". ";
cout << endl;
}
}
数学:
a = {1, 2, 3, 4, 5}
a[[ ⌈ Length[a] Random[] ⌉ ]]
或者,在最近的版本中,简单地说:
RandomChoice[a]
Random[]生成一个0到1之间的伪随机浮点数。它乘以列表的长度,然后使用ceiling函数四舍五入到下一个整数。该索引然后从。
由于哈希表功能在Mathematica中经常使用规则,并且规则存储在列表中,因此可以使用:
a = {"Badger" -> 5, "Bird" -> 1, "Fox" -> 3, "Frog" -> 2, "Wolf" -> 4};
Icon有一个集合类型和一个随机元素操作符,一元“?”,因此表达式
? set( [1, 2, 3, 4, 5] )
将产生1到5之间的随机数。
当程序运行时,随机种子被初始化为0,因此要在每次运行时产生不同的结果,请使用randomize()
既然你说“其他语言的解决方案也欢迎”,下面是Python的版本:
>>> import random
>>> random.choice([1,2,3,4,5,6])
3
>>> random.choice([1,2,3,4,5,6])
4
推荐文章
- 如何格式化Joda-Time DateTime仅为mm/dd/yyyy?
- 使嵌套JavaScript对象平放/不平放的最快方法
- 使用该集合的原因。种子功能
- 如何在POM.xml中引用环境变量?
- 大的Ө符号到底代表什么?
- 如何在android中复制一个文件?
- 将整数转换为字符串,以逗号表示千
- 堆与二叉搜索树(BST)
- 接口方法的最终参数-有什么意义?
- Java中的@UniqueConstraint注释
- 给定一个数字数组,返回所有其他数字的乘积的数组(不除法)
- 如何在清洁模式下运行eclipse ?如果我们这样做会发生什么?
- 关于数据库,每个开发人员应该知道些什么?
- 获取java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory异常
- 广度优先Vs深度优先