Re: compare two sorted array, item by item, which one is bigger

Rainer Weikusat <[email protected]> Tue, 27 Feb 2024 15:37:33 +0000
Newsgroups comp.lang.perl.misc
Message-ID <[email protected]>
Rainer Weikusat <[email protected]> writes:
> hymie! <[email protected]> writes:

[...]

>> foreach $player (sort
>> {$percent{$b} <=> $percent{$a} || ${$scores{$b}}[0] <=> ${$scores{$a}}[0] }
>> keys %percent)
>>
>> which will check the first element in each array from the %scores hash
>> to see which value is larger.
>>
>> The question is -- how can I (or can I) programatically keep checking
>> entries in the arrays of the %scores hash until I find a pair of
>> entries that are not equal?
>
> If you're arrays are always of equal length, you could use
>
> sub ary_cmp
> {
>     my ($a0, $a1) = @_;
>     my $rc;
>
>     for (0 .. $#$a0) {
>         $rc = $$a0[$_] - $$a1[$_];
>         return $rc < 0 ? -1 : 1 if $rc;
>     }
>
>     return 0;
> }

This can be simplified somewhat by using the <=> operator for the check
inside the loop as that already produces the desired result of either
-1, 0 or 1.

sub ary_cmp
{
    my ($a0, $a1) = @_;

    for (0 .. $#$a0) {
        $_ and return $_ for $$a0[$_] <=> $$a1[$_];
    }

    return 0;
}