I have a table that in addition to some data has the n
column storing the index of the next record. For example,
q)show t:([]x:"cbad";n:3 0 1 4)
x n
---
c 3
b 0
a 1
d 4
I am looking for a method to recover the order of the records from this information. In the example above the correct order is abcd
and the n
column tells us that c
is followed by d
, b
is followed by c
, a
is followed by b
, and d
is the last record (note the out of range index in the n
column).
q)select x,next_x:x n from t
x next_x
--------
c d
b c
a b
d
The last record always comes last (at the right place) and the algorithm may assume this.
[EDIT]
Here is a one-liner that I came up with:
q)t exec n\[-1+count n;]first where @[(1+count n)#1b;n;:;0b] from t
x n
---
a 1
b 0
c 3
d 4