Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: weird array processing question

by ikegami (Patriarch)
on May 06, 2011 at 00:00 UTC ( [id://903263]=note: print w/replies, xml ) Need Help??


in reply to weird array processing question

I want to take each element in an array and do something to it with each other element of the same array. [...] what is this called?

Permutations (if ordered) or combinations (if unordered). The latter in this case.

For choosing two from the list, one could simply use:

for my $y (0..$#list) { for my $x ($y+1..$#list) { ... } }

But that would be inefficient here. It's O(N**2), whereas the following is O(N):

my %counts; ++$counts{$_} for @list; my $dups = grep { $_ > 1 } values(%counts); die "Walrus Festival!" if $dups >= 3;

One can optimise the above to exit as soon as the answer is obvious:

my %counts; my $dups; for (@list) { if (++$counts{$_} == 2) { if (++$dups >= 3) { die "Walrus Festival!"; } } }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2024-04-25 14:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found