Search code examples
kdb

How to rearrange array in alternating positive and negative number?


Please help me to write a function to re-arrange positive and negative numbers.

I tried below function, it's not working as expected.

q)list:1 2 3 -4 -1 4    
q)f:{p:count p1:l where (signum l:asc x) <> -1;d:p-count x;n1:count n2:x where (signum x)=-1;(raze ((n2,d#0),'p1)) except 0}
q)f[list]
-4 1 -1 2 3 4

q)list2:    -5 -2 5 2 4 7 1 8 0 -8   //Not working for this input because of length mismatch.

Please provide any suggestions how to handle operations when input parameters x and y are not equal in length to avoid length errors.


Solution

  • May be not the most efficient way, but it's easy to follow.

    {
      p: x where x>=0; 
      n: x where x<0; 
      L: (count p)&count n; 
      (raze (L#n), 'L#p), (L _ n), L _ p
    }
    
    1. Capture positive and negative numbers into n and p lists
    2. Find shorter length L of p and n
    3. Concatenate the first L elements of lists p and n and add leftovers to tail