in reply to How to get the index of smallest whole number in an array?
What I find interesting, and I hope I am not out of my depth here, please correct, is that in one of the four* (?) approaches to a solution, the so-called Schwartzian transform (ST) is used. I think (as I learned about this trick not that long ago) I have spotted ST on tybalt89's, kcott's and AnomalousMonk's solutions.
What I mean is that sort() is passed something different than just the original array or just its indices in the form of additional/pre-processed information. In this case it is the index of each element *as well* as its value in the form of a tuple-ref. E.g. where map passes on to sort [ $_ => $x[$_] ] or () (another trick I learned when you want map to filter(=grep) too). And so, sort does not have to constantly ask for $arr[$a], instead it is given this value and does $a->[1] (which is comparable in overhead but let's ignore this for the sake of argument).
On the other hand, johngg manages without ST because it passes only the index of each element after filtering out non-whole numbers. And so sort() does this: $arr[$a] <=> $arr[$b].
I am not posting any benchmarks because they are totally irrelevant as this is a pet-scenario toy problem.
Now, consider that the problem was the following: For the same array, find the index of the element with the highest prime factor.
This is a blindingly obvious case for the use of ST because there is no contest between:
sort { $a->[1] <=> $b->[1] } map { $arr[$_] >= 0 ? [ $_, max_prime_factor($arr[$_] +) ] : () } 0 .. $#arr
and
sort { max_prime_factor($arr[$a]) <=> max_prime_factor +($arr[$b]) } grep { $arr[ $_ ] >= 0 } 0 .. $#arr
----
four* : 1) swartzian map/sort, 2) non-swartzian map/sort, 3) List::Util et al, 4) PDL
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to get the index of smallest whole number in an array?
by jdporter (Paladin) on Jul 02, 2018 at 16:01 UTC | |
|
Re^2: How to get the index of smallest whole number in an array?
by BrowserUk (Patriarch) on Jul 02, 2018 at 16:22 UTC | |
by bliako (Abbot) on Jul 02, 2018 at 17:25 UTC | |
by AnomalousMonk (Archbishop) on Jul 02, 2018 at 22:46 UTC | |
by bliako (Abbot) on Jul 03, 2018 at 00:02 UTC | |
by Veltro (Hermit) on Jul 03, 2018 at 18:29 UTC | |
by AnomalousMonk (Archbishop) on Jul 03, 2018 at 21:38 UTC |