Re: compare two sorted array, item by item, which one is bigger
hymie! <[email protected]> Wed, 28 Feb 2024 15:35:22 GMT
| Newsgroups | comp.lang.perl.misc |
|---|---|
| Organization | Eric Conspiracy Secret Labs |
| Message-ID | <[email protected]> |
In our last episode, the evil Dr. Lacto had captured our hero, Rainer Weikusat <[email protected]>, who said: > hymie! <[email protected]> writes: >> 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 your arrays are always of equal length, you could use I don't think I can depend on that :( > otherwise, it's a bit more difficult. > > sub ary_cmp > { > my ($a0, $a1) = @_; > my ($last, $rc); > > # we need the length of the shorter array > # start with the length of array a0 > # and see if the length of array a1 is less > $last = $#$a0; > $_ < $last and $last = $_ for $#$a1; > > # for each entry in the shorter array > # compare that numbered entry in the two arrays > # return <=> if the result is not 0 > for (0 .. $last) { > $_ and return $_ for $$a0[$_] <=> $$a1[$_]; > } > > # all of the elements are equal, so return the longer array > return @$a0 <=> @$a1; > } I took the liberty of adding your improvement to this function. I'll definitely try this out and see how well it work. I have a few followup questions... (*) I added some comments. Can you tell me if I'm correct? (*) Could I have set $last this way? $last = $#$a0 < $#$a1 ? $#$a0 : $#$a1 ; or $last = @$a0 < @$a1 ? @$a0 : @$a1 ; ? (*) In this construct > for (0 .. $last) { > $_ and return $_ for $$a0[$_] <=> $$a1[$_]; is it safe to reuse $_ like that? The scoping will work itself out, even without a bracket set? Thank you very much. --hymie!