nth:{*z{((?,/x@*y)_dvl,/y;*y)}[x]/,,y} / jamie -> vrabi -> sa g:,/+:'+(1!;-1!;1!';-1!')@\:1000 -1#!_1e6 / 4-way neighbors of 1k 1k grid \t nth[g;450000]400 / 93ms = 400th nearest neighbors from 450000 \ jon harrop's Ocaml solution: http://www.ffconsultancy.com/products/ocaml_for_scientists/complete/index.html given a graph, possibly containing cycles: 1. The 0th neighbour of a vertex i is the singleton set {i}. 2. The 1st neighbours of vertex i are given in a look-up table. 3. The nth neighbours of i is the union of the neighbours of the n-1th neighbours without the n-1th and n-2th neighbours. / simple circular chain, g i = neighbors of i g:+-1 1!\:!1000 / recursive nth {:[z=0;,y;z=1;x i;(?,/x@*t)_dvl,/t:y _f[x]'z-1 2]} {:[z=0;,y;z=1;x i;{(?,/x y)_dvl y,z}[x]. y _f[x]'z-1 2]} / i.e. join:, flat:join/ distinct:?: union:distinct flat@ singleton:,: without:_dvl first:*: at:@ nth:{[g;i;n] :[n=0 ;singleton[i] n=1 ;at[g;i] without[union[at[g;nth[g;i;n-1]]];join[nth[g;i;n-1];nth[g;i;n-2]]]]} / q (jamie -> sa) {first z{((distinct raze x[first y])except raze y;first y)}[x]/enlist enlist y} / k w/explicit loop {r:,,y;do[z;r:((?,/x@*r)_dvl,/r;*r)];*r} / 2^nth nearest neighbors of all vertices: nth_2:{y{(!#x){(,/y)_dv x}'x x}/x} g:+-1 1!\:!10 nth_2[g;0] (9 1 0 2 1 3 2 4 3 5 4 6 5 7 6 8 7 9 8 0) nth_2[g;1] (8 2 9 3 0 4 1 5 2 6 3 7 4 8 5 9 6 0 7 1) nth_2[g;2] (6 4 7 5 8 6 9 7 0 8 1 9 2 0 3 1 4 2 5 3)