Gangabass has asked for the wisdom of the Perl Monks concerning the following question:
Hi, Monks.
I have a problem finding all permutations of a string. For example given {a|b}cd{f|g|h} i must get:
acdf bcdf acdg ... bcdh
The main problem for me here is that original string may have unknown number of token {} (here we have only two but sometimes it's seven).
Here is my code (but it doesn't produce output i need):
#!/usr/bin/perl -w use strict; use warnings; my $input_text; open my $input_fh, "input.txt" or die $!; { local $/; $input_text = <$input_fh>; } close $input_fh; my @tokens; my $number = 1; while ( $input_text =~ m/\{([^\}]+)}/isxg ) { push @tokens, { values => [ split /\|/, $1 ], name => "%TOKEN_$number%", }; $input_text =~ s/\{([^\}]+)}/%TOKEN_$number%/is; $number++; } foreach my $token_id ( 1 .. scalar(@tokens) ) { foreach my $value ( @{ $tokens[ $token_id - 1 ]->{values} } ) { my $output_text = $input_text; $output_text =~ s/%TOKEN_$token_id%/$value/is; while ( $output_text =~ m{%TOKEN_(\d+)}is ) { my $id = $1; $output_text =~ s/%TOKEN_$id%/$tokens[ $id - 1 ]->{values} +->[0]/is; } print $output_text; #sleep 1; } } sleep 1;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Find all string permutations
by ikegami (Patriarch) on Apr 26, 2010 at 23:15 UTC | |
by Gangabass (Vicar) on Apr 27, 2010 at 00:13 UTC | |
|
Re: Find all string permutations
by toolic (Bishop) on Apr 26, 2010 at 23:07 UTC | |
|
Re: Find all string permutations
by BrowserUk (Patriarch) on Apr 27, 2010 at 00:52 UTC | |
|
Re: Find all string permutations
by repellent (Priest) on Apr 27, 2010 at 05:18 UTC | |
by BrowserUk (Patriarch) on Apr 27, 2010 at 05:24 UTC | |
by repellent (Priest) on Apr 27, 2010 at 05:30 UTC | |
| A reply falls below the community's threshold of quality. You may see it by logging in. |