1

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
Thomas Smyth - Treliant
  • 4,993
  • 6
  • 25
  • 36
Alexander Belopolsky
  • 2,228
  • 10
  • 26

2 Answers2

1

With your assumptions you can do something like:

t exec -2_n\[first i except n] from t

speeds your example up by about 30%, and a bit more elegant I think :-)

Matt

Matt Doherty
  • 101
  • 2
  • 1
    If you haven't seen it before you might also find Stevan Apter's article in vector on treetables pretty interesting (http://archive.vector.org.uk/art10500340) Your problem made me think of it. – Matt Doherty Nov 23 '17 at 10:36
  • Thanks for the link. Very interesting. Unfortunately, when I tried your solution on a larger test case I got a `'loop` error. – Alexander Belopolsky Nov 23 '17 at 20:33
  • 1
    How large is the test case/dataset you are using? – Thomas Smyth - Treliant Nov 23 '17 at 21:00
  • `'loop` is a pretty strange error to see for this. It indicates you have a dependency cycle if you're using views like `a::a`. Any chance your full table has a column called `loop` or something similar? that's the only other thing I can think of... – Matt Doherty Nov 24 '17 at 12:29
0

Someone in office came up with a simplification of your solution:

t exec n\[-1+count i;first i except n]from t

I have a one liner solution of my own, it is not quicker than the one above but it makes use of a dictionary defining what the next char is to get the right order:

{a:-1_r\[key[r]except value r:x[`x]!x[`x]x`n];x a?/:x`x}t
x n
---
a 1
b 0
c 3
d 4
Thomas Smyth - Treliant
  • 4,993
  • 6
  • 25
  • 36