从集合中挑选一个随机元素

时间:2008-09-24 00:12:18

标签: java algorithm language-agnostic random set

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

34 个答案:

答案 0 :(得分:79)

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++;
}

答案 1 :(得分:71)

有点相关你知道吗:

java.util.Collections中有一些有用的方法可以改组整个集合:Collections.shuffle(List<?>)Collections.shuffle(List<?> list, Random rnd)

答案 2 :(得分:32)

使用ArrayListHashMap的快速Java解决方案:[element - &gt;指数]。

动机:我需要一组具有RandomAccess属性的项目,尤其是从集合中选择一个随机项目(请参阅pollRandom方法)。二叉树中的随机导航不准确:树不是完美平衡的,这不会导致均匀分布。

public class RandomSet<E> extends AbstractSet<E> {

    List<E> dta = new ArrayList<E>();
    Map<E, Integer> idx = new HashMap<E, Integer>();

    public RandomSet() {
    }

    public RandomSet(Collection<E> items) {
        for (E item : items) {
            idx.put(item, dta.size());
            dta.add(item);
        }
    }

    @Override
    public boolean add(E item) {
        if (idx.containsKey(item)) {
            return false;
        }
        idx.put(item, dta.size());
        dta.add(item);
        return true;
    }

    /**
     * Override element at position <code>id</code> with last element.
     * @param id
     */
    public E removeAt(int id) {
        if (id >= dta.size()) {
            return null;
        }
        E res = dta.get(id);
        idx.remove(res);
        E last = dta.remove(dta.size() - 1);
        // skip filling the hole if last is removed
        if (id < dta.size()) {
            idx.put(last, id);
            dta.set(id, last);
        }
        return res;
    }

    @Override
    public boolean remove(Object item) {
        @SuppressWarnings(value = "element-type-mismatch")
        Integer id = idx.get(item);
        if (id == null) {
            return false;
        }
        removeAt(id);
        return true;
    }

    public E get(int i) {
        return dta.get(i);
    }

    public E pollRandom(Random rnd) {
        if (dta.isEmpty()) {
            return null;
        }
        int id = rnd.nextInt(dta.size());
        return removeAt(id);
    }

    @Override
    public int size() {
        return dta.size();
    }

    @Override
    public Iterator<E> iterator() {
        return dta.iterator();
    }
}

答案 3 :(得分:27)

这比接受的答案中的for-each循环更快:

int index = rand.nextInt(set.size());
Iterator<Object> iter = set.iterator();
for (int i = 0; i < index; i++) {
    iter.next();
}
return iter.next();

for-each构造在每个循环上调用Iterator.hasNext(),但是从index < set.size()开始,该检查是不必要的开销。我看到速度提高10-20%,但是YMMV。 (此外,这无需添加额外的返回语句即可编译。)

请注意,此代码(以及大多数其他答案)可以应用于任何集合,而不仅仅是Set。通用方法形式:

public static <E> E choice(Collection<? extends E> coll, Random rand) {
    if (coll.size() == 0) {
        return null; // or throw IAE, if you prefer
    }

    int index = rand.nextInt(coll.size());
    if (coll instanceof List) { // optimization
        return ((List<? extends E>) coll).get(index);
    } else {
        Iterator<? extends E> iter = coll.iterator();
        for (int i = 0; i < index; i++) {
            iter.next();
        }
        return iter.next();
    }
}

答案 4 :(得分:15)

如果要在Java中执行此操作,则应考虑将元素复制到某种随机访问集合(例如ArrayList)中。因为,除非您的设置很小,否则访问所选元素将是昂贵的(O(n)而不是O(1))。 [编辑:列表副本也是O(n)]

或者,您可以查找更符合您要求的其他Set实现。来自Commons Collections的ListOrderedSet看起来很有希望。

答案 5 :(得分:8)

在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())]);
}

答案 6 :(得分:8)

List asList = new ArrayList(mySet);
Collections.shuffle(asList);
return asList.get(0);

答案 7 :(得分:3)

Clojure解决方案:

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

答案 8 :(得分:2)

Perl 5

@hash_keys = (keys %hash);
$rand = int(rand(@hash_keys));
print $hash{$hash_keys[$rand]};

这是一种方法。

答案 9 :(得分:2)

上面的解决方案就延迟而言,但并不能保证选择每个索引的概率相等 如果需要考虑,请尝试水库采样。 http://en.wikipedia.org/wiki/Reservoir_sampling
Collections.shuffle()(由少数人建议)使用一种这样的算法。

答案 10 :(得分:2)

C ++。这应该相当快,因为​​它不需要迭代整个集合或对其进行排序。这应该与大多数现代编译器一起开箱即用,假设它们支持tr1。如果没有,您可能需要使用Boost。

Boost docs有助于解释这一点,即使您不使用Boost。

诀窍是利用数据已分成存储桶的事实,并快速识别随机选择的存储桶(具有适当的概率)。

//#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;
  }
}

答案 11 :(得分:1)

如何

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

答案 12 :(得分:1)

在Java 8中:

itertuples()

答案 13 :(得分:1)

这与接受的答案(Khoth)相同,但删除了不必要的sizei变量。

    int random = new Random().nextInt(myhashSet.size());
    for(Object obj : myhashSet) {
        if (random-- == 0) {
            return obj;
        }
    }

虽然废除了上述两个变量,但上述解决方案仍然是随机的,因为我们依赖随机(从随机选择的索引开始)在每次迭代时将自身递减到0

答案 14 :(得分:1)

既然你说“欢迎使用其他语言的解决方案”,这里是Python的版本:

>>> import random
>>> random.choice([1,2,3,4,5,6])
3
>>> random.choice([1,2,3,4,5,6])
4

答案 15 :(得分:1)

Javascript解决方案;)

function choose (set) {
    return set[Math.floor(Math.random() * set.length)];
}

var set  = [1, 2, 3, 4], rand = choose (set);

或者:

Array.prototype.choose = function () {
    return this[Math.floor(Math.random() * this.length)];
};

[1, 2, 3, 4].choose();

答案 16 :(得分:1)

你不能只获得集合/数组的大小/长度,生成0和大小/长度之间的随机数,然后调用索引与该数字匹配的元素吗? HashSet有一个.size()方法,我很确定。

在伪代码中 -

function randFromSet(target){
 var targetLength:uint = target.length()
 var randomIndex:uint = random(0,targetLength);
 return target[randomIndex];
}

答案 17 :(得分:1)

在Mathematica中:

a = {1, 2, 3, 4, 5}

a[[ ⌈ Length[a] Random[] ⌉ ]]

或者,在最近的版本中,只需:

RandomChoice[a]

这得到了一次投票,也许是因为它没有解释,所以这里有一个:

Random[]生成0到1之间的伪随机浮点数。这将乘以列表的长度,然后使用ceiling函数向上舍入到下一个整数。然后从a中提取该索引。

由于哈希表功能经常使用Mathematica中的规则完成,并且规则存储在列表中,因此可以使用:

a = {"Badger" -> 5, "Bird" -> 1, "Fox" -> 3, "Frog" -> 2, "Wolf" -> 4};

答案 18 :(得分:1)

PHP,假设“set”是一个数组:

$foo = array("alpha", "bravo", "charlie");
$index = array_rand($foo);
$val = $foo[$index];

Mersenne Twister函数更好,但在PHP中没有MT等价的array_rand。

答案 19 :(得分:1)

不幸的是,在任何标准库集合容器中都无法有效地完成(优于O(n))。

这很奇怪,因为向哈希集和二进制集添加随机选择函数非常容易。在不稀疏的哈希集中,您可以尝试随机条目,直到获得命中。对于二叉树,您可以在左子树或右子树之间随机选择,最多为O(log2)步。我已经实现了下面的演示:

import random

class Node:
    def __init__(self, object):
        self.object = object
        self.value = hash(object)
        self.size = 1
        self.a = self.b = None

class RandomSet:
    def __init__(self):
        self.top = None

    def add(self, object):
        """ Add any hashable object to the set.
            Notice: In this simple implementation you shouldn't add two
                    identical items. """
        new = Node(object)
        if not self.top: self.top = new
        else: self._recursiveAdd(self.top, new)
    def _recursiveAdd(self, top, new):
        top.size += 1
        if new.value < top.value:
            if not top.a: top.a = new
            else: self._recursiveAdd(top.a, new)
        else:
            if not top.b: top.b = new
            else: self._recursiveAdd(top.b, new)

    def pickRandom(self):
        """ Pick a random item in O(log2) time.
            Does a maximum of O(log2) calls to random as well. """
        return self._recursivePickRandom(self.top)
    def _recursivePickRandom(self, top):
        r = random.randrange(top.size)
        if r == 0: return top.object
        elif top.a and r <= top.a.size: return self._recursivePickRandom(top.a)
        return self._recursivePickRandom(top.b)

if __name__ == '__main__':
    s = RandomSet()
    for i in [5,3,7,1,4,6,9,2,8,0]:
        s.add(i)

    dists = [0]*10
    for i in xrange(10000):
        dists[s.pickRandom()] += 1
    print dists

我得到[995,975,971,995,1057,1004,966,1052,984,1001]作为输出,所以分布接缝很好。

我为自己努力解决同样的问题,而且我还没有确定天气,这个更高效的选择的性能增益值得使用基于python的集合的开销。我当然可以对它进行改进并将其转换为C,但这对我来说太过分了:)

答案 20 :(得分:1)

在lisp中

(defun pick-random (set)
       (nth (random (length set)) set))

答案 21 :(得分:1)

在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"]);

答案 22 :(得分:1)

Icon有一个集类型和一个随机元素运算符,一元“?”,所以表达式

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

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

当程序运行时,随机种子初始化为0,因此要在每次运行时使用randomize()

生成不同的结果

答案 23 :(得分:0)

为了好玩,我写了一个基于拒绝采样的RandomHashSet。有点hacky,因为HashMap不允许我们直接访问它的表,但它应该可以正常工作。

它不使用任何额外的内存,查找时间为O(1)摊销。 (因为java HashTable很密集)。

class RandomHashSet<V> extends AbstractSet<V> {
    private Map<Object,V> map = new HashMap<>();
    public boolean add(V v) {
        return map.put(new WrapKey<V>(v),v) == null;
    }
    @Override
    public Iterator<V> iterator() {
        return new Iterator<V>() {
            RandKey key = new RandKey();
            @Override public boolean hasNext() {
                return true;
            }
            @Override public V next() {
                while (true) {
                    key.next();
                    V v = map.get(key);
                    if (v != null)
                        return v;
                }
            }
            @Override public void remove() {
                throw new NotImplementedException();
            }
        };
    }
    @Override
    public int size() {
        return map.size();
    }
    static class WrapKey<V> {
        private V v;
        WrapKey(V v) {
            this.v = v;
        }
        @Override public int hashCode() {
            return v.hashCode();
        }
        @Override public boolean equals(Object o) {
            if (o instanceof RandKey)
                return true;
            return v.equals(o);
        }
    }
    static class RandKey {
        private Random rand = new Random();
        int key = rand.nextInt();
        public void next() {
            key = rand.nextInt();
        }
        @Override public int hashCode() {
            return key;
        }
        @Override public boolean equals(Object o) {
            return true;
        }
    }
}

答案 24 :(得分:0)

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];

答案 25 :(得分:0)

您也可以将该集转移到数组使用数组 它可能会在小范围内工作我看到最多投票答案中的for循环无论如何都是O(n)

Object[] arr = set.toArray();

int v = (int) arr[rnd.nextInt(arr.length)];

答案 26 :(得分:0)

如果你真的只想选择&#34;任何&#34;来自Set的对象,对随机性没有任何保证,最简单的是取迭代器返回的第一个。

    Set<Integer> s = ...
    Iterator<Integer> it = s.iterator();
    if(it.hasNext()){
        Integer i = it.next();
        // i is a "random" object from set
    }

答案 27 :(得分:0)

Java 8最简单的是:

outbound.stream().skip(n % outbound.size()).findFirst().get()

其中n是一个随机整数。当然,它的性能低于for(elem: Col)

答案 28 :(得分:0)

使用Khoth的答案作为起点的通用解决方案。

/**
 * @param set a Set in which to look for a random element
 * @param <T> generic type of the Set elements
 * @return a random element in the Set or null if the set is empty
 */
public <T> T randomElement(Set<T> set) {
    int size = set.size();
    int item = random.nextInt(size);
    int i = 0;
    for (T obj : set) {
        if (i == item) {
            return obj;
        }
        i++;
    }
    return null;
}

答案 29 :(得分:0)

如果设置的大小不大,那么可以使用Arrays。

int random;
HashSet someSet;
<Type>[] randData;
random = new Random(System.currentTimeMillis).nextInt(someSet.size());
randData = someSet.toArray();
<Type> sResult = randData[random];

答案 30 :(得分:0)

使用Guava,我们可以做得比Khoth的回答好一点:

public static E random(Set<E> set) {
  int index = random.nextInt(set.size();
  if (set instanceof ImmutableSet) {
    // ImmutableSet.asList() is O(1), as is .get() on the returned list
    return set.asList().get(index);
  }
  return Iterables.get(set, index);
}

答案 31 :(得分:0)

Java 8+ 流:

    static <E> Optional<E> getRandomElement(Collection<E> collection) {
        return collection
                .stream()
                .skip(ThreadLocalRandom.current()
                .nextInt(collection.size()))
                .findAny();
    }

基于 answerJoshua Bone 但略有变化:

  • 忽略 Streams 元素顺序以稍微提高并行操作的性能
  • 使用当前线程的 ThreadLocalRandom
  • 接受任何集合类型作为输入
  • 返回提供的 Optional 而不是 null

答案 32 :(得分:-1)

如果你不介意第三方库,Utils库有一个IterableUtils,它有一个randomFrom(Iterable iterable)方法,它将接受一个Set并从中返回一个随机元素它

Set<Object> set = new HashSet<>();
set.add(...);
...
Object random = IterableUtils.randomFrom(set);

它位于Maven Central Repository:

<dependency>
  <groupId>com.github.rkumsher</groupId>
  <artifactId>utils</artifactId>
  <version>1.3</version>
</dependency>

答案 33 :(得分:-2)

阅读完这篇帖子后,我写的最好的是:

static Random random = new Random(System.currentTimeMillis());
public static <T> T randomChoice(T[] choices)
{
    int index = random.nextInt(choices.length);
    return choices[index];
}