Iterate/sort associative array by value?
Cym13
cpicard at openmailbox.org
Sun Apr 7 16:24:52 UTC 2019
On Sunday, 7 April 2019 at 15:41:51 UTC, Robert M. Münch wrote:
> I have an AA int[ulong] and would like to traverse the AA from
> biggest to smallest by value. Is there an elegant way to do
> this?
>
> The only way I can imagine is to create an "reverse" AA of the
> form ulong[int] and than sort by keys. Traverse this AA and use
> the value as the lookup key in the orginial array. But this
> feels all a bit wired...
You could use sort to gather the indexes in order then traverse
from there:
aa.byKey.array.sort!((a, b) => aa[a]<aa[b])
With a wrapper caching that order and making it transparent as
well as update on insertion (which should be in log(n) since you
know have an ordered list of indexes, you can use dichotomy to
update the indexes without walking all your AA again) I think you
could have a nice little container.
However if double entry is necessary maybe a simpler 2D array
would be easier to work with?
More information about the Digitalmars-d-learn
mailing list