Re: compare two sorted array, item by item, which one is bigger
Rainer Weikusat <[email protected]> Mon, 26 Feb 2024 16:20:55 +0000
| Newsgroups | comp.lang.perl.misc |
|---|---|
| Message-ID | <[email protected]> |
hymie! <[email protected]> writes: > I have two people, 0 and 1, which are denoted by the $player variable. > > I have a hash of sorted arrays > > @{$scores{$player}} > 104 92 92 90 87 > 104 92 92 89 88 > > And I have a %percent hash that holds the sum of those elements. > In this case, $percent{$player} is 465 for both. [...] > So I have this construct > > foreach $player (sort {$percent{$b} <=> $percent{$a}} keys %percent) > > that will sort the %percent hash by value ... but since the two are > equal, I think I'm getting a random choice. > > So then I wrote this construct > > 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; } otherwise, it's a bit more difficult. sub ary_cmp { my ($a0, $a1) = @_; my ($last, $rc); $last = $#$a0; $_ < $last and $last = $_ for $#$a1; for (0 .. $last) { $rc = $$a0[$_] - $$a1[$_]; return $rc < 0 ? -1 : 1 if $rc; } return @$a0 <=> @$a1; } could do.