Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: help writing simple perl script

by Ieronim (Friar)
on Jul 27, 2006 at 16:53 UTC ( [id://564165]=note: print w/replies, xml ) Need Help??


in reply to help writing simple perl script

Two completely different subs, the first is much faster, the second is much more flexible. You need to replace @ary with your actual data :)
#!/usr/bin/perl use warnings; use strict; my @ary = (0..5); print map { "@$_\n" } pairs(@ary); print "\nCHOOSE:\n"; print map { "@$_\n" } choose(2, @ary); # hard-coded return of pairs sub pairs { my @result; foreach my $i (0..$#_-1) { foreach my $j ($i+1..$#_) { push @result, [$_[$i], $_[$j]]; } } return @result; } #more general solution: choose any combinations of k elms from @_: sub choose { no warnings 'recursion'; my $k = shift; my @ary = @_; my $n = scalar @ary; return if ($k > $n) || ($k < 1); if ($k == 1) { return map { [$_] } @ary; } my @AoA; foreach my $i (0..($n-$k)) { push @AoA, map { [$ary[$i], @{$_}] } choose($k-1, @ary[ $i+1.. +$#ary ]); } return @AoA; }

     s;;Just-me-not-h-Ni-m-P-Ni-lm-I-ar-O-Ni;;tr?IerONim-?HAcker ?d;print

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://564165]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2024-04-20 02:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found