@Test public void multipleChoices() { final Supplier<Integer> s = new RandomSupplier.Builder<Integer>().withChoice(1, 33).withChoice(2, Suppliers.of(33.5)) .withChoice(3, Suppliers.of(33)).withRandom(new Random()).build(); final Map<Integer, Integer> counts = Maps.newHashMap(); counts.put(1, 0); counts.put(2, 0); counts.put(3, 0); for (int i = 0; i < 100; i++) { final int value = s.get(); counts.put(value, counts.get(value) + 1); } for (final int count : counts.values()) { assertThat(count, greaterThan(0)); } }
@Override public T get() { final double totalWeight = getCurrentWeights(); final double rnd = this.random.nextDouble() * totalWeight; double previousWeights = 0.0; for (final Choice<T> choice : this.choices) { if (rnd < previousWeights + choice.currentWeight) { return choice.value; } previousWeights += choice.currentWeight; } throw new IllegalStateException("Incorrect weight calculation"); }
RandomSupplier implements Supplier<T> { @Override public T get() { final double totalWeight = getCurrentWeights(); final double rnd = this.random.nextDouble() * totalWeight; double previousWeights = 0.0; for (final Choice<T> choice : this.choices) { if (rnd < previousWeights + choice.currentWeight) { return choice.value; } previousWeights += choice.currentWeight; } throw new IllegalStateException("Incorrect weight calculation"); } }
RandomSupplier implements Supplier<T> { @Override public T get() { final double totalWeight = getCurrentWeights(); final double rnd = this.random.nextDouble() * totalWeight; double previousWeights = 0.0; for (final Choice<T> choice : this.choices) { if (rnd < previousWeights + choice.currentWeight) { return choice.value; } previousWeights += choice.currentWeight; } throw new IllegalStateException("Incorrect weight calculation"); } private  RandomSupplier(final Builder<T> builder); }
RandomSupplier implements Supplier<T> { @Override public T get() { final double totalWeight = getCurrentWeights(); final double rnd = this.random.nextDouble() * totalWeight; double previousWeights = 0.0; for (final Choice<T> choice : this.choices) { if (rnd < previousWeights + choice.currentWeight) { return choice.value; } previousWeights += choice.currentWeight; } throw new IllegalStateException("Incorrect weight calculation"); } private  RandomSupplier(final Builder<T> builder); @Override T get(); @Override String toString(); }
RandomSupplier implements Supplier<T> { @Override public T get() { final double totalWeight = getCurrentWeights(); final double rnd = this.random.nextDouble() * totalWeight; double previousWeights = 0.0; for (final Choice<T> choice : this.choices) { if (rnd < previousWeights + choice.currentWeight) { return choice.value; } previousWeights += choice.currentWeight; } throw new IllegalStateException("Incorrect weight calculation"); } private  RandomSupplier(final Builder<T> builder); @Override T get(); @Override String toString();  }