JSFiddle - React, Tailwind, and code Playground

by Daniel Cheung

HTML

<p>Here is a game where there is a dozen of eggs. There are 8 hard-boiled eggs and 4 raw eggs. 2 players takes turn cracking eggs on their heads and the first to crack 2 raw eggs on their heads loses.</p>

<p>Player A always starts first.</p>

<input type="number" id="n" value="100000">
<button id="run">Run simulation</button>
<pre id="results"></pre>

JavaScript

$(function(){
  $("#run").click(function(){
  	var scores = {a:0, b:0};
    var n = Math.abs(parseInt($("#n").val()));
    console.log(n);
    for (var i = 0; i < n; i++) {
      var eggs = ["r","r","r","r","h","h","h","h","h","h","h","h"];
      var players = {A:2, B:2};
      var turnA = true;
      //items[Math.floor(Math.random()*items.length)];
      while (eggs.length > 1) {
        var p = (turnA ? "A" : "B");
        turnA = !turnA;
        var index = Math.floor(Math.random()*eggs.length);
        if (eggs[index] == "r")
          players[p] --;
        eggs.splice(index,1);
        if (players[p] == 0) {
          scores[(turnA ? "a" : "b")]++;
          break;
        }
      }
      if (i == n-1) {
        //end simulation
        console.log(scores);
        $("#results").text(
          "A wins: " + (scores.a/n*100).toFixed(3) + "%\n" +
          "B wins: " + (scores.b/n*100).toFixed(3) + "%"
        )
      }
    }
  });
})