root/examples/phonewords.pl

Revision 13741, 1.5 kB (checked in by audreyt, 2 years ago)

* Massive cleanup: qw() and q() is no longer quotes but functions,

and q:to/END/ is now expression-level construct.

  • Property svn:mime-type set to text/plain; charset=UTF-8
  • Property svn:eol-style set to native
Line 
1# Generates all the combinations of letters that can be made from all
2# the combinations of the last 4 digits of a phone number.
3#
4# For more details, see:
5#    http://www.perlmonks.org/index.pl?node_id=453821
6#
7# CAUTION: Produces a lot of output and takes a long time to complete.
8
9use v6-alpha;
10
11my %digit_letters = (
12    2 => [<a b c>],
13    3 => [<d e f>],
14    4 => [<g h i>],
15    5 => [<j k l>],
16    6 => [<m n o>],
17    7 => [<p r s>],
18    8 => [<t u v>],
19    9 => [<w x y>],
20);
21
22my @letterchoices;
23
24my $letters;
25my $letterchooser = choose([0 .. 2], 4);
26while $letters = $letterchooser() {
27    push @letterchoices, $letters;
28}
29
30my $digits;
31my $digitchooser = choose([2 .. 9], 4);
32while $digits = $digitchooser() {
33    my $letters;
34    for @letterchoices -> $letters {
35        my @digits  = split '', $digits;
36        my @letters = split '', $letters;
37
38        my @word;
39
40        for each(@digits; @letters) -> $digit, $letter {
41            push @word, %digit_letters{$digit}[$letter];
42        }
43
44        say "$digits: ", @word;
45    }
46}
47
48sub basen ($base, $num) {
49    my $q = int($num / $base);
50    my $r =     $num % $base;
51
52    return $r if $q == 0;
53    return basen($base, $q), $r;
54}
55
56sub choose ($list, $number) {
57    my $iterations = $list.elems ** $number;
58    my $current = 0;
59
60    return sub {
61        return if $current >= $iterations;
62
63        my @choice = basen($list.elems, $current++);
64        unshift @choice, 0 while @choice.elems < $number;
65
66        return @choice.map({$list[$_]}).join("");
67    };
68}
Note: See TracBrowser for help on using the browser.