Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

(Golf) Ordered Combinations

by MeowChow (Vicar)
on Apr 25, 2001 at 00:45 UTC ( #75261=obfuscated: print w/ replies, xml ) Need Help??

The challenge is to write a sub that takes the paramters ($length, @symbols) and produces an ordered list of all sequnces of length $length that are combinations of characters from the list @symbols. The output ordering is based on the order of @symbols. Assume that @symbols is a list comprised of any quantity of one-byte ASCII chars.

My current attempt at 52 chars:

sub c{my$n=-1+shift;$n?map{my$c=$_;map$c.$_,c($n,@_)}@_:@_}
Example:
print join " ", c qw(2 a b c d); print "\n"; print join " ", c qw(4 0 1); # outputs aa ab ac ad ba bb bc bd ca cb cc cd da db dc dd 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 +1110 1111
Good luck, and may your efforts yield little code :)
   MeowChow                                   
               s aamecha.s a..a\u$&owag.print

Comment on (Golf) Ordered Combinations
Select or Download Code
Re: (Golf) Ordered Combinations
by sachmet (Scribe) on Apr 25, 2001 at 01:42 UTC
    51 :-)
    #!/usr/bin/perl sub c {my$n=-1+shift;$n?map{my$c=$_;map$c.$_,c($n,@_)}@_:@_}; sub d {my$n=shift;--$n?map{my$d=$_;map$d.$_,d($n,@_)}@_:@_}; print join " ", c qw(2 a b c); print "\n"; print join " ", d qw(2 a b c); print "\n"; print join " ", c qw(4 0 1); print "\n"; print join " ", d qw(4 0 1); print "\n";
Re: (Golf) Ordered Combinations
by satchboost (Scribe) on Apr 25, 2001 at 01:55 UTC
    I know that I'm bending the rules a little, but this does get below 50.

    sub c{my$n=pop;--$n?map{my$c=$_;map$c.$_,c(@_,$n)}@_:@_}

    Example:

    print join " ", c qw(a b c 2); print "\n"; print join " ", c qw(0 1 4); print "\n";
Re (tilly) 1: (Golf) Ordered Combinations
by tilly (Archbishop) on Apr 25, 2001 at 06:51 UTC
    If we don't have to be strict compliant...49.
    sub c { @r='';@r=map{$c=$_;map$c.$_,@r}@_ for 1..shift;@r }
    (Note: I handle the case of $n=0 correctly. The solution that you started with does not...)
      (Note: I handle the case of $n=0 correctly. The solution that you started with does not...)

      I can't slip anything past you, can I? :-)

         MeowChow                                   
                     s aamecha.s a..a\u$&owag.print
        Is there any way to print these results to a file?

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: obfuscated [id://75261]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2014-08-01 04:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (256 votes), past polls