pchou has asked for the wisdom of the Perl Monks concerning the following question:
I'm trying to write an automated cryptogram solver using perl. I am limiting this program to merely solving simple substitution cipers. For those of you who don't know, here is an example of a substitution ciper:
cryptogram:
DVYXUEQVKO IEAJVR: WEETOKVT UMSR XKQJ ZEL! DEOJ WKDT EBUJZ!
solution:
CRYPTOGRAM LOVERS: BOOKMARK THIS PAGE NOW! COME BACK OFTEN!
Thre is a 1:1 correspondence between the letters for the entire cryptogram.
My idea is to attack it brute force using /usr/dict/words to get potential words for each word in the cryptogram, then get a partial cipher alphabet for each word, and finally recurse through all the partial ciphers for one that matches the most (or mismatches the least with the others). If any of you think this is idea could be improved please let me know.
Anyway, the first part is for me to write a program that, when given a word, will list all possibilities.
For example, "ABCC" will yield "ball", "less", "tree", etc. I have code that will do this, but there is a bug. For example, when I give it "ABCA", it should give me the word "that", but it should not give me the word "noon", but it does. Can someone help me find the bug?
#!/usr/bin/perl -w use strict; use vars '@dict'; open(DICT, '</usr/dict/words') || die "/usr/dict/words: $!\n"; chomp(@dict = <DICT>); close DICT; sub match_crypto { my @pattern = split //, $_[0]; my (@letters,%slots,@matches); WORDS: foreach my $word (@dict) { next unless length $word == @pattern; @letters = split //, $word; %slots = (); for (my $i = 0; $i < @letters; ++$i) { next WORDS if $letters[$i] eq $pattern[$i]; if (exists $slots{$pattern[$i]}) { next WORDS unless $slots{$pattern[$i]} eq $letters[$i]; } else { $slots{$pattern[$i]} = $letters[$i]; } } push @matches, $word; } @matches; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Cryptogram Solver
by I0 (Priest) on Mar 23, 2001 at 06:28 UTC | |
|
Re: Cryptogram Solver
by mr.nick (Chaplain) on Mar 23, 2001 at 05:14 UTC | |
by pchou (Novice) on Mar 23, 2001 at 06:39 UTC | |
|
Re: Cryptogram Solver
by buckaduck (Chaplain) on Mar 23, 2001 at 05:19 UTC | |
|
Re: Cryptogram Solver
by lhoward (Vicar) on Mar 23, 2001 at 05:14 UTC | |
|
Re: Cryptogram Solver
by 2501 (Pilgrim) on Mar 26, 2001 at 06:30 UTC | |
|
Re: Cryptogram Solver
by Anonymous Monk on Aug 12, 2011 at 10:03 UTC |