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.
<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);
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.