Here is a better version.  I realized just after I sent it that
@string was unnecessary.  Originally I was going to write romanize and
expand in the same function, and I didn't go back and simplify
romanize when I decided to split the functionality into two functions.
 Also, I had a useless join in expand due to a possible different
solution (the code worked, but was pointless).  This version also
correctly handles being passed an empty string.

#!/usr/bin/perl

use strict;
use warnings;

my %map = (
        a => [ qw/ aa ab 12 / ],
        e => ['y'],
);

for my $word (qw/ bad bed base attack /, '') {
        print "$word =>\n",
                map "\t$_\n", expand(romanize($word, \%map));
}


#produce a compact representation of the possible strings
sub romanize {
        my ($word, $map) = @_;

        return map { [ $map->{$_} ? @{$map->{$_}} : $_ ] } split //, $word;
}

#expand the compact representation into all possible strings
sub expand {
        my @string = @_;
        my @result;

        return ""            if @string == 0;
        return @{$string[0]} if @string == 1;

        for my $char (@{$string[0]}) {
                for my $string (expand(@string[1 .. $#string])) {
                        push @result, "$char$string";
                }
        }
        
        return @result;
}



-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to