Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Lottery combinations golf

by barrachois (Pilgrim)
on Oct 14, 2003 at 02:41 UTC ( #299009=note: print w/replies, xml ) Need Help??


in reply to Lottery combinations golf

#!/usr/bin/perl -w use strict; # ----------------------------------------------- # Here's some golf-ish code that loops through the # given combinations, as well as a clearer rendition. # It uses a hash to eliminate duplicates, and # strings rather than an array for each combo. # I expect it can be done in many fewer strokes, # but I had fun playing around with it, anyway, # and this four liner looked obfuscated enough. # The output is listed at the end. my($N,$M)=(8,6);my%c;r($N,join('',1..$N));sub r{my($n,$s)=@_;if($n==$M){$c{$s}++unless$c{$s};}else {for(1..$N){$t=~s/$_/#/,r($n-1,$t)if(our$t=$s)=~/$_/;}}} print join($/,sort keys %c),"$/Total=",scalar(keys %c),$/; _END__ # A clearer version of the same thing. my ($N,$M) = (8,6); my %combos = (); recursive($N,join('',1..$N)); sub recursive { my ($n,$combo) = @_; if ($n==$M){ $combos{$combo}++ unless $combos{$combo}; } else { for my $i (1..$N){ if ( (my $tmp=$combo) =~ /$i/ ){ $tmp=~s/$i/#/; recursive($n-1,$tmp); } } } } print "-- Combinations of $N things with ", $N-$M, " crossed out. --\n", join("\n", sort keys %combos), "\n-- Total number is ", scalar(keys %combos), ". --\n\n"; # -------- output of the short one ------------- ##345678 #2#45678 #23#5678 #234#678 #2345#78 #23456#8 #234567# 1##45678 1#3#5678 1#34#678 1#345#78 1#3456#8 1#34567# 12##5678 12#4#678 12#45#78 12#456#8 12#4567# 123##678 123#5#78 123#56#8 123#567# 1234##78 1234#6#8 1234#67# 12345##8 12345#7# 123456## Total=28

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://299009]
help
Chatterbox?
[hippo]: Thanks for your input which has soothed my sanity (a little)
[Corion]: Eily: Sure - if you force both things into stringy things, then you break that magic. But that would also mean that you changed the expression, as now $x = 0.00 will be true instead of false as it were before
[Corion]: Ah no, at least in my feeble experiments that doesn't change the meaning
[Corion]: We sell sanity in small packages ;)
[Eily]: oh, boolean context uses the "" overload if no bool overload has been defined
[Eily]: (I wondered if overloading bool was actually necessary)

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (11)
As of 2017-07-27 13:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I came, I saw, I ...
























    Results (414 votes). Check out past polls.