漂流排序是“排序”数组的一种简单方法。它通过“滑动”或“旋转”数组中的元素来工作,直到数组被排序,或者直到数组无法排序。
让我们来看两个例子。首先,考虑数组[10, 2, 3, 4, 7]。由于数组没有排序,所以我们只旋转一次。(这可以发生在任何一个方向,只要它保持相同的方向。)然后,数组变成:
[7, 10, 2, 3, 4]这是没有排序的,所以我们再次旋转。
[4, 7, 10, 2, 3]又一次:
[3, 4, 7, 10, 2]最后一次:
[2, 3, 4, 7, 10]而且已经解决了!因此,数组[10, 2, 3, 4, 7]是可漂移的。为了清晰起见,下面是数组的所有旋转:
[10, 2, 3, 4, 7]
[7, 10, 2, 3, 4]
[4, 7, 10, 2, 3]
[3, 4, 7, 10, 2]
[2, 3, 4, 7, 10]现在考虑数组[5, 3, 9, 2, 6, 7]。看看它的旋转:
[5, 3, 9, 2, 6, 7]
[7, 5, 3, 9, 2, 6]
[6, 7, 5, 3, 9, 2]
[2, 6, 7, 5, 3, 9]
[9, 2, 6, 7, 5, 3]
[3, 9, 2, 6, 7, 5]这些数组都没有排序,因此数组[5, 3, 9, 2, 6, 7]是不可漂移的。
目标将非空数组/整数列表作为程序/函数的输入,在输入和输出上实现漂移排序,如果不能对输入/函数进行漂移排序,则输出falsey值(或空数组/列表)。整数绑定到语言max/ min,但最大值必须至少为255,最小为0。
您可以使用内置的排序方法,但不能使用内置的方法来解决挑战。
这是一个密码-高尔夫,所以是以字节为单位的最短程序。
input => output
[1] => [1]
[5, 0, 5] => [0, 5, 5]
[3, 2, 1] => false
[0, 9, 3] => false
[1, 2, 3, 4] => [1, 2, 3, 4]
[4, 1, 2, 3] => [1, 2, 3, 4]
[0, 2, 0, 2] => false
[5, 3, 9, 2, 6, 7] => false
[0, 0, 0, 0, 0, 0, 0] => [0, 0, 0, 0, 0, 0, 0]
[75, 230, 30, 42, 50] => [30, 42, 50, 75, 230]
[255, 255, 200, 200, 203] => [200, 200, 203, 255, 255]发布于 2016-04-21 19:12:08
ṙỤċṢȧṢ在网上试试!或验证所有测试用例.
ṙỤċṢȧṢ Main link. Argument: A (list)
Ụ Grade up; return the indices of A, sorted by their corresponding values.
ṛ Rotate A by each index, yielding the list of all rotations.
Ṣ Yield A, sorted.
ċ Count the number of times sorted(A) appears in the rotations.
This gives 0 if the list isn't driftsortable.
ȧṢ Logical AND with sorted(A); replaces a positive count with the sorted list.发布于 2016-04-21 18:24:14
->a{a.any?{a.sort==a.rotate!}&&a}对于数组中的每个元素,a.any?最多会触发一次,除非它在数组变异为排序状态后立即停止(并返回true)。如果发生这种情况,我们将返回变异的数组。否则,我们将返回any?返回的虚值。
发布于 2016-04-21 18:11:28
lambda l:sorted(l)*(map(cmp,l[-1:]+l,l).count(1)<3)不需要旋转。相反,对列表进行排序,然后通过检查循环列表中的连续元素是否最多减少一次来查看原始列表是否可以漂移排序。计数是<3,因为map将较短的列表与None放在末尾,从而增加了假的减少。
https://codegolf.stackexchange.com/questions/78173
复制相似问题