If you haven't heard of
Monkeys Typing Shakespeare: Infinity Theory, here is a brief overview.
The theory is that if you had an infinite number of monkeys typing at random (as monkeys would) on an infinite number of typewriters for an infinite number of years, it is probable that one would eventually type out the entire works of Shakespeare.
A good explination of this theory is here. After reading that, you will see that it would take a monkey years and years to type out a sonet. But, with an infinite number of monkeys, it should only take a few years.
Now, what does this have to do with Perl? Well, during my morning cup of coffee, I decided I wanted to be a monkey (since I don't own one), and made a quick hack which mimics a monkey typing randomly on a 27 key keyboard, 26 letters, and a space bar (I added 5 spaces, since the space bar is large, and helps speed things up).
I have it pointing to a log file, so I can later parse what was typed. If you too become a monkey, remember that this is a slow process, and an infinite number of us is the only thing that could raise the probability. After running this for a while, I see the monkey mainly gets small words correct. If you have changes for this (like adding in the use of the Ispell module, or anything to quicken it or make it more 'life-like' (remember, this was a quick hack to amuse myself), let me know!
#!/usr/bin/perl -w
use strict;
no strict 'subs';
# 27 letters and a space bar (5 spaces since the space bar is large :)
+.
my @keys = (A..Z, ' ', ' ', ' ', ' ', ' ');
# Open log to print good words
open(FH, ">>monkey.log") or die "No monkey ($!)";
select(FH); $|++;
# Start a block
{
my $str;
# Building a 572 char string, could be longer.
for (1..572) {
$str .= $keys[rand(@keys)];
}
my @words = split(" ",$str);
for (@words) {
# Not too many 15+ char words, so skip em
next if /\w{15,}/;
my @spell = `echo $_ | ispell -a -S`;
if (grep /^\*/, @spell) {
# Good monkey!
print $_ . " " unless !/[IA]/;
next;
}
}
# Keep redoing this block
redo;
}
See also: RFC2795, Infinite Monkey Protocol Suite
Cheers,
KM
In reply to Be a monkey!
by KM
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.