ベクトルに一連のオブジェクトがあり、そこからランダムなサブセットを選択したい (例: 100 個のアイテムが戻ってきて、ランダムに 5 個を選択する)。私の最初の (非常に性急な) パスでは、非常に単純で、おそらく過度に巧妙な解決策を実行しました。
Vector itemsVector = getItems();
Collections.shuffle(itemsVector);
itemsVector.setSize(5);
これには素晴らしくシンプルであるという利点がありますが、あまりうまく拡張できないと思います。つまり、 Collections.shuffle() は少なくとも O(n) でなければなりません。私のあまり賢くない代替手段は
Vector itemsVector = getItems();
Random rand = new Random(System.currentTimeMillis()); // would make this static to the class
List subsetList = new ArrayList(5);
for (int i = 0; i < 5; i++) {
// be sure to use Vector.remove() or you may get the same item twice
subsetList.add(itemsVector.remove(rand.nextInt(itemsVector.size())));
}
コレクションからランダムなサブセットを引き出すより良い方法について何か提案はありますか?