Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the index of the maximum value in a list in Perl 6?

Tags:

raku

It's easy enough to find the maximum value in a list in Perl 6:

> my @list = 1,4,9,7,3;
> say @list.max;
9

But if I want to find the index of the maximum entry, there doesn't seem to be an elegant way to do this.

> say (^@list).sort({ -@list[$_] })[0];
2
> say @list.pairs.sort(*.value).tail.key;
2
> say @list.first(@list.max, :k);
2

Those all work, but they're hardly elegant, let alone efficient.

Is there a better way to do this?

It'd be nice if max had :k, :v and :kv options, like for instance first has. Of course, there might not be a unique index (for instance, in the case of (1,4,9,7,9).max, but then again, there might not be a unique value either:

> dd (1, 2.0, 2.0e0, 2).max;
2.0
> say <the quick brown fox>.max(*.chars);
quick

max already retrieves the first maximum value, so it would be perfectly reasonable to return the first index with :k (or :kv).

like image 531
mscha Avatar asked Jan 09 '17 18:01

mscha


People also ask

How do I find the maximum value in an array in Perl?

Note: In Perl arrays, the size of an array is always equal to (maximum_index + 1) i.e. And you can find the maximum index of array by using $#array.

What is the max index of an array?

max index(es) is the index for the first max value. If array is multidimensional, max index(es) is an array whose elements are the indexes for the first maximum value in array. min value is of the same data type and structure as the elements in array. min index(es) is the index for the first min value.


1 Answers

You can use

@list.maxpairs

to get a list of all pairings of indices and maximal values or

@list.pairs.max(*.value).key

to get just a single index.

As far as I can see, both maxpairs and the ability to provide a transformation to max are still undocumented.

like image 180
Christoph Avatar answered Sep 19 '22 18:09

Christoph