From 7c20be157cb183f014bf7aaa2126928cdb2a834d Mon Sep 17 00:00:00 2001 From: kiran Date: Thu, 23 Jul 2009 21:00:19 +0000 Subject: [PATCH] Added ability to sample from a list *without* replacement. git-svn-id: file:///humgen/gsa-scr1/gsa-engineering/svn_contents/trunk@1304 348d0f76-0448-11de-a6fe-93d51630548a --- .../broadinstitute/sting/utils/ListUtils.java | 44 +++++++++++++++---- 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/java/src/org/broadinstitute/sting/utils/ListUtils.java b/java/src/org/broadinstitute/sting/utils/ListUtils.java index d8581c06d..b79b2ab0a 100644 --- a/java/src/org/broadinstitute/sting/utils/ListUtils.java +++ b/java/src/org/broadinstitute/sting/utils/ListUtils.java @@ -1,9 +1,6 @@ package org.broadinstitute.sting.utils; -import java.util.List; -import java.util.HashSet; -import java.util.ArrayList; -import java.util.Random; +import java.util.*; /** * Created by IntelliJ IDEA. @@ -16,8 +13,14 @@ public class ListUtils { static Random rand = new Random(12321); //System.currentTimeMillis()); + /** + * Returns n random indices drawn with replacement from the range 0..(k-1) + * + * @param n the number of random indices to draw (with replacement) + * @param k the total number of indices allowed + * @return a list of random indices ranging from 0 to (k-1) with possible duplicates + */ static public ArrayList sampleIndicesWithReplacement(int n, int k) { - // Returns n random indices drawn with replacement from the range 1..k ArrayList chosen_balls = new ArrayList (); for (int i=0; i ArrayList sliceListByIndices(List indices, List list) { - // Given a list of indices into a list, return those elements of the list with the possibility - // of drawing list elements multiple times + /** + * Returns n random indices drawn without replacement from the range 0..(k-1) + * + * @param n the number of random indices to draw (without replacement) + * @param k the total number of indices allowed + * @return a list of random indices ranging from 0 to (k-1) without duplicates + */ + static public ArrayList sampleIndicesWithoutReplacement(int n, int k) { + ArrayList chosen_balls = new ArrayList(k); + for (int i = 0; i < n; i++) { + chosen_balls.add(i); + } + + Collections.shuffle(chosen_balls, rand); + + //return (ArrayList) chosen_balls.subList(0, k); + return new ArrayList(chosen_balls.subList(0, k)); + } + + /** + * Given a list of indices into a list, return those elements of the list with the possibility of drawing list elements multiple times + + * @param indices the list of indices for elements to extract + * @param list the list from which the elements should be extracted + * @param the template type of the ArrayList + * @return a new ArrayList consisting of the elements at the specified indices + */ + static public ArrayList sliceListByIndices(List indices, List list) { ArrayList subset = new ArrayList(); for (int i : indices) {