Skip to content

Instantly share code, notes, and snippets.

/Simulation

Created Jun 27, 2015
Embed
What would you like to do?
Simulation of picking from a changing number of marbles
import java.util.*;
public class Main {
private static final long SIMULATIONS = 100000000;
private static final long NUMBER_OF_PICKS = 4;
private static final Random RANDOM = new Random();
public static void main(String[] args) {
Map<Color, Long> pickCounts = new HashMap<>();
for (Color color : Color.values()) {
pickCounts.put(color, 0L);
}
for (int i = 0; i < SIMULATIONS; ++i) {
List<Color> bag = createBag();
for (int j = 0; j < NUMBER_OF_PICKS; ++j) {
Color pickedMarble = pickAndRemoveOther(bag);
long updatedCount = pickCounts.get(pickedMarble) + 1;
pickCounts.put(pickedMarble, updatedCount);
}
}
System.out.println("SIMULATED PROBABILITIES");
for (Color color : Color.values()) {
double probability = pickCounts.get(color) * 1.0d / SIMULATIONS;
System.out.println(color.toString() + ": " + probability);
}
}
private static Color pickAndRemoveOther(List<Color> bag) {
int pick = RANDOM.nextInt(bag.size());
Color pickedMarble = bag.get(pick);
Iterator<Color> bagIterator = bag.iterator();
while (bagIterator.hasNext()) {
Color bagColor = bagIterator.next();
if (bagColor.equals(pickedMarble)) {
bagIterator.remove();
}
}
return pickedMarble;
}
private static List<Color> createBag() {
List<Color> bag = new ArrayList<>(20);
for (Color color : Color.values()) {
for (int i = 0; i < color.getBagCount(); ++i) {
bag.add(color);
}
}
return bag;
}
private enum Color {
BLUE (8),
RED (6),
GREEN (3),
WHITE (2),
BLACK (1);
private int bagCount;
Color(int bagCount) {
this.bagCount = bagCount;
}
public int getBagCount() {
return bagCount;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.