1

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;
}
}
  • Not sure, but my own simulations match the theoretical results. – Samadin May 15 '17 at 23:39
  • 1
    This class is far more complicated than it should be for the problem described in the article. I don't know why you think this is what you should simulate, but it is not what the NYT article described. For one thing, it is possible in the original question that chicks 2, 3, 4, and 5 peck chicks 1, 2, 5, and 6, respectively, ending with 3 and 4 unpecked, but your simulation says the pecking must continue until either 3 or 4 gets pecked. Count the number of pecks: there should be exactly 100 in every simulation. I bet you have more than that. – David K May 15 '17 at 23:43

0 Answers0