Search code examples
perlcross-product

Words for phone number


I would like to write an simple perl script to generate all possible words for given phone number.

I started with definition of an array:

my @nums = (
    ['0'],
    ['1'],
    ['2', 'a', 'b', 'c'],
    ['3', 'd', 'e', 'f'],
    ['4', 'g', 'h', 'i'],
    ['5', 'j', 'k', 'l'],
    ['6', 'm', 'n', 'o'],
    ['7', 'p', 'q', 'r', 's'],
    ['8', 't', 'u', 'v'],
    ['9', 'w', 'x', 'y', 'z']
);

The final script should generate following output:

$ num2word 12
12
1a
1b
1c

$ num2word 213
213
21d
21e
21f
a13
a1d
a1e
a1f
b13
b1d
b1e
b1f
c13
c1d
c1e
c1f

I am looking for any module which can do most part of the job (something like List::Permutor which does not seem to qualify for this task).

Any hints? Thanks!


Solution

  • Our very own @brian d foy has solved this problem with his Set::CrossProduct module.

    use Set::CrossProduct;
    my $iterator = Set::CrossProduct->new(
        [ [ qw(8 t u v) ], [ qw(0) ], [ qw(7 p q r s) ] ] );
    print "@$_\n" for $iterator->combinations;
    

    Output:

    8 0 7
    8 0 p
    8 0 q
    8 0 r
    8 0 s
    t 0 7
    t 0 p
    t 0 q
    t 0 r
    t 0 s
    u 0 7
    u 0 p
    u 0 q
    u 0 r
    u 0 s
    v 0 7
    v 0 p
    v 0 q
    v 0 r
    v 0 s