I went through the question "Expected number of unpecked chicks - NYT article" and tried to create a simulation for it. However, the result is not something I expected based on the answers to above question. Can somebody explain the reasons behind this. I consistently get a value between 33 and 40. Here is the code.
import java.util.Arrays;
import java.util.Random;
public class PeckingOrder {
Random randomChick = new Random();
Random leftOrRight = new Random();
boolean[] chicks = new boolean[100];
public PeckingOrder() {
Arrays.fill(chicks, true);
}
public static void main(String[] args) {
PeckingOrder order = new PeckingOrder();
System.out.println("New experiment");
while (!order.noMoreFights()) {
int chickId = order.pickChick();
int peckedChickId = order.peck(chickId);
if (peckedChickId != -1)
order.showOrder(peckedChickId);
}
System.out.println("Unpecked count " + order.countUnpecked());
}
private void showOrder(int peckedChickId) {
for (int i = 0; i < chicks.length; i++) {
if (i == peckedChickId)
System.out.print("2");
else
System.out.print(chicks[i] ? 1 : 0);
}
System.out.println();
}
private int pickChick() {
return randomChick.nextInt(chicks.length);
}
private int peck(int chickId) {
if (chicks[chickId]) {
int peckedChick = -1;
if (peckLeft()) {
peckedChick = chickId == 0 ? chicks.length - 1 : chickId - 1;
} else {
peckedChick = chickId == chicks.length - 1 ? 0 : chickId + 1;
}
if (chicks[peckedChick]) {
chicks[peckedChick] = false;
return peckedChick;
}
}
return -1;
}
private boolean peckLeft() {
return leftOrRight.nextBoolean();
}
private boolean noMoreFights() {
if (chicks[0] && chicks[chicks.length - 1])
return false;
for (int i = 0; i < chicks.length - 1; i++) {
if (chicks[i] && chicks[i + 1])
return false;
}
return true;
}
private int countUnpecked() {
int count = 0;
for (int i = 0; i < chicks.length; i++) {
if (chicks[i])
count++;
}
return count;
}
}