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

Re: Efficient selection mechanism?

by davido (Cardinal)
on Jan 14, 2014 at 16:56 UTC ( [id://1070573]=note: print w/replies, xml ) Need Help??


in reply to Efficient selection mechanism?

Convert this AoA:

my @control = ( [ 2, 13, 3, 16 ], [ 10, 1, 11, 6 ], );

To this...

# 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <-- Indicies rep +resent original ints. my @control = ( [ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, ], [ 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, ], );

So that you can take a test array, "@test = ( 1, 4, 7, 9 )" and ask if sum(@{control[$n]}[@test]) == 0

If you turn off warnings for undefined values in addition, you won't even need to worry about placing zeros; only place '1' where needed. ;)

That becomes an O(n) solution that benefits from the fact that array slices are fast, and List::Util::sum is XS. Wrap it in a grep, and it should fly:

my @valid_row_ix = grep { sum( @{$control[$_]}[@test] ) == 0 } 0 .. $# +control;

Update:

I'm not benchmarking, but it might be useful instead to try:

my @valid_row_ix = grep { List::MoreUtils::none { $_ == 1 } @{$control +[$_]}[@test] } 0 .. $#control;

...since it will short-circuit out of the "none" loop as soon as a 1 is detected, whereas 'sum' will look at all elements in your test array. However, the "$_==1" portion drops from XS back into a MULTICALL pure-Perl sub, which is more computationally expensive per iteration than a simple sum. Since the array you're testing seems to be small, my bet is with the 'sum' solution.


Dave

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2024-04-25 15:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found