Finding the index of the maximum value in an associative array

Lyle via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue May 30 15:06:47 PDT 2017


On Tuesday, 30 May 2017 at 18:05:02 UTC, cym13 wrote:
> On Tuesday, 30 May 2017 at 17:57:04 UTC, Lyle wrote:
>> Hi,
>>
>> I have an associative array of type int[ulong] and I'm trying 
>> to get the index of the maximum value, like this:
>>
>> int[ulong] aa = [1UL: 2000,
>>                  2UL: 5000,
>>                  5UL: 1000];
>>
>> writeln(aa.maxIndex); // should print 2
>>
>> Can anyone help me out?
>>
>> Many thanks,
>> Lyle
>
> Simple enough: get all key/values pairs in the AA, and ask for 
> the element which is the maximum relatively to the value, then 
> take its key.
>
>     auto maxIndex(int[ulong] aa) {
>         import std.algorithm;
>
>         return aa.byKeyValue
>                  .maxElement!(x => x.value)
>                  .key;
>     }

Thank you! I used this solution in the end. I had looked at the 
.byKeyValue and .byPair methods but they didn't seem to work - 
turns out I was using an old DMD version!


More information about the Digitalmars-d-learn mailing list