Skip to content

Instantly share code, notes, and snippets.

@maxsilver
Created September 12, 2010 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxsilver/576596 to your computer and use it in GitHub Desktop.
Save maxsilver/576596 to your computer and use it in GitHub Desktop.
The infinite monkey theorem states that a monkey hitting keys at random on a typewriter keyboard for an infinite amount of time will almost surely type a given text, such as the complete works of William Shakespeare. http://en.wikipedia.org/wiki/Infinite_
# A million monkeys
# at a million typewriters
# banging on the keys until they have
# the works of Shakespere
# http://en.wikipedia.org/wiki/Infinite_monkey_theorem
puts "Randomly generate Shakespere"
# Number of randomly generated phrases
counter = 0
# Have we created Shakespere yet?
finished = false
# The word/quote/phrase to generate
search = "to be or not to be".downcase
# search all lowercase letters and spaces
chars = ("a".."z").to_a << " "
# calculate the mathematical probability of
# the machine generating this string on any given run
probability = chars.length ** search.length
until finished
counter += 1
generated = ""
1.upto(search.length) { |i| generated << chars[rand(chars.size)] }
puts counter.to_s + " -- " + generated
if generated == search
puts %{
The machine has randomly generated "#{search}"
At an improbability rate of #{counter} to 1 and falling.
The statistical probability of this occuring is #{probability} to 1
Except in maths, nothing is impossible, just extremely improbable.
}%
finished = true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment