给定一个整数列表,找出无限期地向右移动所指示的步骤所产生的“轨迹”(如果是负数),必要时从第一个元素开始包装。
此处的“轨迹”定义为一份清单,其中载有只访问一次的元素,按访问顺序排列,以及包含反复访问的元素的清单,也是按以下顺序排列的:
[first, second, ...], [first_of_loop, second_of_loop, ...]请注意:
给定的
[6, 0, -6, 2, -9 , 5, 3]我们
6开始3,-6,2,5,2。因此轨迹是
[6, 3, -6], [2, 5]...where第二个列表显示最后一个循环(我们首先遇到2,然后是5,然后永远循环)。
in out
[0] [], [0]
[3] [], [3]
[-1, 2] [-1], [2]
[5, 2, 4, 6, 7, 3, 1] [], [5, 3, 2, 6, 4, 1]
[6, 0, -6, 2, -9 ,5 ,3] [6, 3, -6], [2, 5]
[4, 5, 2, 6, -2, 7, 8] [4], [-2, 2]
[6, 10, 10, 0, -9, -4, 6] [6, 6], [-4, 10, -9, 10]
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9] [], [9, 9, 9, 9]发布于 2021-08-15 22:02:55
a=>[(g=p=>a=1/(i=g[p%=w=a.length])?[]:[q=a[p],...g(p+q+w*q*q,g[p]=k++)])(k=0).splice(0,i),a]a => [ // a[] = input array
( g = p => // g is a recursive function taking a position p
// the underlying object of g is also used to keep
// track of the positions that are visited
a = // update a[]
1 / ( //
i = g[ // reduce the position modulo the length w of the
p %= w = // array and load g[p] into i
a.length //
] //
) ? // if i is defined:
[] // we've found the loop: stop the recursion
: // else:
[ // update the output array:
q = a[p], // load a[p] into q
...g( // do a recursive call:
p + q + // add q to p
w * q * q, // also add w*q² to make sure it's >= 0
g[p] = k++ // save the index k into g[p] and increment k
) // end of recursive call
] // end of array update
)(k = 0) // initial call to g with p = k = 0
.splice(0, i), // extract the non-looping part
a // append the looping part
] //发布于 2021-08-15 20:54:57
^:iT(Yy+a@y%:#a)NiiPBya@i^@:i@?y将列表(格式化为:[1;2;-3])作为命令行参数,并输出两个列表的列表。在这里试试!或,验证所有测试用例在TIO。
^:iT(Yy+a@y%:#a)NiiPBya@i^@:i@?y
a is cmdline input, eval'd (-x flag);
i is 0, y is "" (implicit)
^:i Split i and assign back to i: i is now [0]
T Loop until
y current index
+a@y plus number at current index
%: mod
#a length of list
Y (yank into y, making this the new index)
( )Ni is already in the list of indices traversed:
iPBy Push the new index onto the list of indices
After the loop, we have the list of unique
indices traversed in i and the first repeated
index in y
a@i Values from a at each index in i
^@: split at
i@?y the index of y in ihttps://codegolf.stackexchange.com/questions/233424
复制相似问题