Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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


In reply to Re: Efficient selection mechanism? by davido
in thread Efficient selection mechanism? by BrowserUk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2024-04-24 20:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found