http://www.perlmonks.org?node_id=927688


in reply to An exploration of higher-level-language approaches to the "First all-zero row in an NxN matrix" problem (goto Considered Harmful)

Using List::Util->sum() and grep seems to work.

knoppix@Microknoppix:~$ perl -MList::Util=sum -E ' > @array = ( > [ qw{ 1 1 1 1 1 } ], > [ qw{ 0 1 1 0 0 } ], > [ qw{ 0 0 0 0 1 } ], > [ qw{ 0 0 0 0 0 } ], > [ qw{ 0 1 0 1 0 } ], > [ qw{ 0 0 0 0 0 } ], > ); > say qq{First all-zero row is @{ [ > ( grep { ! sum @{ $array[ $_ ] } } 0 .. $#array )[ 0 ] ] }};' First all-zero row is 3 knoppix@Microknoppix:~$

I hope this is of interest.

Update: I'm stupid! It's even simpler to use List::Util->first() instead of grep.

knoppix@Microknoppix:~$ perl -MList::Util=sum,first -E ' > @array = ( > [ qw{ 1 1 1 1 1 } ], > [ qw{ 0 1 1 0 0 } ], > [ qw{ 0 0 0 0 1 } ], > [ qw{ 0 0 0 0 0 } ], > [ qw{ 0 1 0 1 0 } ], > [ qw{ 0 0 0 0 0 } ], > ); > say q{First all-zero row is }, > first { ! sum @{ $array[ $_ ] } } 0 .. $#array;' First all-zero row is 3 knoppix@Microknoppix:~$

Update 2: Stupid and naive :-( List::Util->sum() is not a good tool as it will fail on something as simple as the new second row below. Using a List::Util->first() within another List::Util->first() might be better.

knoppix@Microknoppix:~$ perl -MList::Util=first -E ' > @array = ( > [ qw{ 1 1 1 1 1 } ], > [ qw{ 1 0 0 -1 0 } ], > [ qw{ 0 1 1 0 0 } ], > [ qw{ 0 0 0 0 1 } ], > [ qw{ 0 0 0 0 0 } ], > [ qw{ 0 1 0 1 0 } ], > [ qw{ 0 0 0 0 0 } ], > ); > > $found = first { > $i = $_; > $res = first { > $array[ $i ]->[ $_ ] != 0 > } 0 .. $#{ $array[ $i ] }; > ! defined $res; > } 0 .. $#array; > say > q{First all-zero row is -> }, > defined $found > ? $found > : q{none found}; > ' First all-zero row is -> 4 knoppix@Microknoppix:~$

Cheers,

JohnGG

  • Comment on Re: An exploration of higher-level-language approaches to the "First all-zero row in an NxN matrix" problem (goto Considered Harmful)
  • Select or Download Code

Replies are listed 'Best First'.
Re^2: An exploration of higher-level-language approaches to the "First all-zero row in an NxN matrix" problem (goto Considered Harmful)
by BrowserUk (Patriarch) on Sep 24, 2011 at 22:59 UTC

    But how many individual values are tested? (Ie. grep will examine an entire row even if the first value in that row is non-zero. Etc.)


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

      I think I've seen it written somewhere that List::Util->first() will efficiently break out as soon as it finds the first item that passes the condition rather than testing all of the items. I've tried to confirm this by looking at the module source but failed to find the relevant code :-s

      Cheers,

      JohnGG