Search code examples
groupingd

How to make pairs from Range?


I have got range MySQLTablesRange. It's consist data like: aa_1 aa_3 aa_2 bb_2 bb_1 bb_3

I need to create pairs like: aa_1 bb_1 aa_2 bb_2 aa_3 bb_3

std.algorithm have method group that doing similar thing, but I do not know how to write it in code. I did:

MySQLTablesRange.each!(a => a.split("_")[1].array.group.writeln);

But it's wrong, because group works with array, but not with single element.

Any ideas?


Solution

  • Update: After testing this - I realised it's not 'group' you want. But chunkBy. Updated the answer to reflect that. https://dlang.org/phobos/std_algorithm_iteration.html#chunkBy

    You have to tell chunkBy how to chunk the data...

    [1,2,3,4,5,6]
        .sort!((a,b) => a%2 > b%2)        // separate odds n evens
        .chunkBy!((a,b) => a%2 == b%2);   // chunk them so all evens are in one range, odds in another.
    

    That will create two groups. One with odd numbers, one with evens.

    In your case it looks like you'd group them on the text that comes after '_' in each element.

    "aa_1 aa_2 aa_3 bb_1 bb_2 bb_3 cc_1"
        .split(" ")
        .sort!((a,b) => a[$-1].to!int < b[$-1].to!int) // sort it so _1's are together, _2s are together. etc
        .chunkBy!((a,b) => a[$-1] == b[$-1]) // chunk them so they're in they're own range
        .each!writeln;   // print each range
    
    $ rdmd test.d
    ["aa_1", "bb_1", "cc_1"]
    ["aa_2", "bb_2"]
    ["aa_3", "bb_3"]
    

    Ideally you'd get index of _ and compare after that...