Search code examples
kdb

How to efficiently get the counts of values (from a list) less than some index number?


It is hard for me to describe in words what this function does, but I have some working code.

f:{[n;k] sum flip k </: til n}
i:i: 3 4 6 7 13;
f[30;i]
0 0 0 0 1 2 2 3 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5i

In am concerned that the flip operation may be expensive for large input values. Is there a way to do this without the flip that is more efficient?

Being just as concise would be a nice-to-have.


Solution

  • For your inputs you can achieve the same result with

    {[n;k] k binr til n}
    

    This should work so long as k remains in ascending order. Docs for binr are here: https://code.kx.com/q/ref/bin/