range result in Tuple! and how to convert into assocArray by sort?
forkit
forkit at gmail.com
Thu May 12 03:18:42 UTC 2022
On Tuesday, 10 May 2022 at 03:22:04 UTC, MichaelBi wrote:
> s is the string, and print result as following:
>
> s.array.sort!("a<b").group.assocArray.byPair.array.sort!("a[0]<b[0]").each!writeln;
>
> Tuple!(dchar, "key", uint, "value")('A', 231)
> Tuple!(dchar, "key", uint, "value")('C', 247)
> Tuple!(dchar, "key", uint, "value")('G', 240)
> Tuple!(dchar, "key", uint, "value")('T', 209)
>
> then how to transfer into
> [['A',231],['C',247],['G',240],['T',209]]? tried map!, but can
> only sortout key or value... tried array(), but result is not
> sorted then...thanks in advance.
Adding tuples to an AA is easy.
Sorting the output of an AA is the tricky part.
// -----
module test;
@safe:
import std;
void main()
{
uint[dchar] myAA;
Tuple!(dchar, uint) myTuple;
myTuple[0] = 'C'; myTuple[1] = 247;
myAA[ myTuple[0] ] = myTuple[1];
myTuple[0] = 'G'; myTuple[1] = 240;
myAA[ myTuple[0] ] = myTuple[1];
myTuple[0] = 'A'; myTuple[1] = 231;
myAA[ myTuple[0] ] = myTuple[1];
myTuple[0] = 'T'; myTuple[1] = 209;
myAA[ myTuple[0] ] = myTuple[1];
// NOTE: associative arrays do not preserve the order of the
keys inserted into the array.
// See: https://dlang.org/spec/hash-map.html
// if we want the output of an AA to be sorted (by key)..
string[] orderedKeyPairSet;
foreach(ref key, ref value; myAA.byPair)
orderedKeyPairSet ~= key.to!string ~ ":" ~
value.to!string;
orderedKeyPairSet.sort;
foreach(ref str; orderedKeyPairSet)
writeln(str);
/+
A:231
C:247
G:240
T:209
+/
}
// --------
More information about the Digitalmars-d-learn
mailing list