Infinite Monkey

An experiment to see how long it would take JavaScript to randomly create just one small line of Shakespeare. Inspired by the idea of infinite monkeys sitting randomly typing on an infinite number of typewriters.

by Lance Concannon

HTML

<div id="words">

</div>

<br>
<span id="count"></span> random characters generated so far.

<div id="result">Phrase not matched yet.</div>

JavaScript

var phrase = "to be or not to be"; //this is the phrase we're trying to match
var count = 0; //want to count how many  characters it takes 

tick();

function tick() { //this is the main loop

  phrase = phrase.slice(1); //remove first char from string
  phrase = phrase + randChar(); //add a random char to end of string
  document.getElementById("words").innerHTML = phrase; //write new string to screen
  count++; //increment count
  document.getElementById("count").innerHTML = count; //write new count to screen
  if (phrase === "to be or not to be") { // inform user if we've stumbled on the right phrase
    document.getElementById("result").innerHTML = phrase;
  }
  requestAnimationFrame(tick);
}


function randChar() { //generate a random character - all lower case for simplicity
  var chars = " abcdefghijklmnopqurstuvwxyz";
  return chars.substr(Math.floor(Math.random() * 27), 1);
}