kdb+

get index from list where value is zero occurring at the last of list


How do we efficiently get index from list where value is zero occurring at the last of list covering the below 4 cases

If list has zero in it in between the list and after that numbers folows then retun the index of the zero where there is no numbers going forward, in this case index 11

list1:0.1085667 0.1034029 0.07207211 0.1463173 0 0.04980147 0.1341839 0.1463173 0.07423638 0.1646141 0.1219965 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
list1[11]

If the list starts and it has zero continous till end of list then return the first encountered list index, in this case index 1

list2:3.44794 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
list2[1]

If list has last zero then return that last index of that zero, in this case index 6

list3:0.09008773 0.2049645 0.2023211 0.307903 0.1754935 0.1354404 0 
list3[6]

If the list has NO last zero then return the last index in that case, in this case index 13

list4:0.1087913 0.06930553 0.07835767 0.09794708 0.07840132 0.06930553 0.05958885 0.1191777 0.06930553 0.07840132 0.05958885 0.1149965 0.1352321 0.05958885
list4[13]

So far I had came up but it works for some cases and doest work for some. I can add if else and handle cases differently but then solution will be lengthy and then would have to pack it in function. Wondering if we can do this in short, efficiently and cleaner way?

first where 0=list1<>0

Solution

  • Another approach:

    q){(-1+count x)&1+last where 0<>x}each(list1;list2;list3;list4)
    11 1 6 13
    

    EDIT: below approach is unreliable, see comments.

    q){(-1+count x)&(0=x)binr 1b}each(list1;list2;list3;list4)
    11 1 6 13