Search code examples
kdb

Distribute elements of one list over elements of another list


I have two lists:

l1:`a`b`c;
l2: til 20;

I am trying to create a dictionary 'd' that contains the elements of 'l1' as key and the elements of 'l2' evenly distributed over it. So like this:

d:(`a`b`c)!(0j, 3j, 6j, 9j, 12j, 15j, 18j;1j, 4j, 7j, 10j, 13j, 16j, 19j;2j, 5j, 8j, 11j, 14j, 17j)

The order of the elements is not relevant, I just need them balanced. I was able to achieve that in an iterative way (happy to add the code, if that's considered helpful), but there must be a more elegant way (potentially with adverbs?).


Solution

  • It can be done using the group :

    q)group (count[l2]#l1)
    (`a`b`c)!(0j, 3j, 6j, 9j, 12j, 15j, 18j;1j, 4j, 7j, 10j, 13j, 16j, 19j;2j, 5j, 8j, 11j, 14j, 17j)
    

    If your l2 is something else instead of til 20 , then you have to lookup the items back after grouping :

    q)l2: 20#.Q.a
    q)l2
    "abcdefghijklmnopqrst"
    q)l2 group (count[l2]#l1)     // lookup the items back from l2 after grouping 
    (`a`b`c)!("adgjmps";"behknqt";"cfilor")