Binomial coefficient using generic Typ
With generic typ List
/** * random Sampling without repeat (Binomail coefficient: n choose m) * * @param items * A list with basic Data * @param m * the number of desired Samples * @param seed * the initial seed * @return A list with obtained Samples */ public static <E> List<E> randomSample(List<E> items, int m, long seed) { if (m > items.size()) { System.err.println("m should smaller than the items.size():" + items.size()); System.exit(-1); } Random rnd = new Random(seed); for (int i = 0; i < m; i++) { int pos = i + rnd.nextInt(items.size() - i); E tmp = items.get(pos); items.set(pos, items.get(i)); items.set(i, tmp); } return items.subList(0, m); }
With generic typ Array
/** * random Sampling without repeat * * @param items * An array with basic Data * @param m * the number of desired Samples * @param seed * the initial seed * @return A array with obtained Samples */ public static <E> E[] randomSample2(E[] items, int m, long seed){ if (m > items.length) { System.err.println("m should smaller than the items.size():" + items.length); System.exit(-1); }else if (items.length <=1) { System.err.println("items can't be empty" + items.length); System.exit(-1); } Random rnd = new Random(seed); for (int i = 0; i < m; i++) { int pos = i + rnd.nextInt(items.length - i); E tmp = items[pos]; items[pos] = items[i]; items[i] = tmp; } E[] result = Arrays.copyOf(items, m); return result; }