in reply to Getting combinations from a number's digits

Generally, this is a combinatorial problem and there are modules to handle that. Here's another way which is only practical due to the small length of the entry. I run the combinations through hash keys to uniquify them. The regex match serves to both extract the digits and validate the input.

#!/usr/bin/perl -w # filename: combo use strict; my $entry = shift; my @array = $entry =~ m/^(\d)(\d)(\d)$/ ? ($1.$2.$3, $1.$3.$2, $2.$1.$3, $2.$3.$1, $3.$1.$2, $3.$2.$1) : (); @array or die "Bad input: ${entry}\n"; @array = do { my %hash; @hash{@array} = (); keys %hash; }; print "${entry} was entered.", " The different combinations would be @{array}.\n"; __END__ $ perl combo 123 123 was entered. The different combinations would be 231 123 312 321 2 +13 132. $ perl combo 122 122 was entered. The different combinations would be 221 212 122.

You will be better off with an array instead of distinct named variables. It will accomodate the smaller number of combinations that are possible with duplicated digits, and you don't have to make up meaningful names for unmeaningful distinctions. (Yes, @array and %hash are not meaningful names outside tutorial use ;-)

After Compline,
Zaxo

Replies are listed 'Best First'.
Re^2: Getting combinations from a number's digits
by PerceptiveJohn (Acolyte) on Jul 10, 2006 at 01:34 UTC
    The line after: my @array =, could you explain the $entry line. Thank you.

      Sure. That uses the "trinary operator", which has the form foo ? bar : baz. It tests foo, whatever that may be, for truth. If true the expression evaluates to bar, if false, to baz.

      Here, foo corresponds to a regular expression match with $entry. The regex tests that $entry consists of exactly three digits and captures the three to $1, $2 and $3 by surrounding each digit's slot with parentheses.

      The bar element is an explicit list of combinations using the captured digits, whatever they may be. It will be returned to the @array assignment by the expression if the match succeeded. The "baz" element is an empty list, which goes to the assignment if the match failed.

      It is important to never use the backreference variables $1,$2,... unless the regex match succeeded. The trinary op above complies with that, since the number variables only appear in the true branch.

      The trinary op is documented in perlop. ++bobf for suggesting the link.

      After Compline,
      Zaxo