Driftsort is a simple way to "sort" an array. It works by "sliding" or "rotating" the elements over in the array until the array is sorted, or until the array fails to be sorted.
Let's walk through two examples. First, consider the array [10, 2, 3, 4, 7]
. Since the array is not sorted, we rotate it once. (This can happen in either direction, so long as it remains the same direction.) Then, the array becomes:
[7, 10, 2, 3, 4]
This is not sorted, so we rotate again.
[4, 7, 10, 2, 3]
And again:
[3, 4, 7, 10, 2]
And a final time:
[2, 3, 4, 7, 10]
And it's sorted! So the array [10, 2, 3, 4, 7]
is driftsortable. Here are all the rotations of the array, for clarity:
[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]
Consider now the array [5, 3, 9, 2, 6, 7]
. Look at its rotations:
[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]
None of these arrays are sorted, so the array [5, 3, 9, 2, 6, 7]
is not driftsortable.
Objective Given a nonempty array/list of integers as input to a program/function, implement driftsort on the input and output it, or output a falsey value (or an empty array/list) if it cannot be driftsorted. The integers are bound to your languages max/min, but this must be at least 255 for the max, and 0 for the min.
You may use built-in sorting methods, but not a built-in which solves the challenge.
This is a code-golf, so the shortest program in bytes.
Test cases
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]
sorted(l)
is a contiguous sublist ofl+l
. \$\endgroup\$shiftsort
? \$\endgroup\$shift
operation that removes the first element of an array. \$\endgroup\$