package jetbrains.buildServer.serverSide; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * @author Eugene Petrenko * Created: 31.03.2010 19:48:09 */ public class Randomization { private final RandomGenerator myRandom; public Randomization(RandomGenerator random) { myRandom = random; } public T selectOneOf(Collection items, double probability) { if (items.size() == 0) throw new RuntimeException("Collection is empty. Nothing to select"); if (items.size() == 1) return items.iterator().next(); for(int i = 0; i < 10 * items.size(); i++) { for (T item : items) { if (itHappend(probability)) { return item; } } } return items.iterator().next(); } private boolean itHappend(double probability) { return myRandom.getRandom().nextDouble() <= probability; } public Collection selectSomeOf(Collection items, double probability) { Set set = new HashSet(items); for (Iterator iterator = set.iterator(); iterator.hasNext();) { iterator.next(); if (!itHappend(probability)) { iterator.remove(); } } return set; } }