Inspired by this StackOverflow post
Given a list where each element appears a maximum of 2 times, we can define it's "sortedness" as the sum of the distances between equal elements. For example, consider
[1,1,2,3,3] (array)
0 1 2 3 4 (indices)
The sortedness of this array is \$2\$. The distance between the 1
s is \$1 - 0 = 1\$, the distance between the 2
s is \$2 - 2 = 0\$ (as there's only one 2
) and this distance between the 3
s is \$4 - 3 = 1\$. Summing these distances, we get the sortedness as \$1 + 0 + 1 = 2\$.
Now, consider
[1,3,2,1,3] (array)
0 1 2 3 4 (indices)
The sortedness of this array is \$6\$:
1
s: \$3 - 0 = 3\$2
s: \$2 - 2 = 0\$3
s: \$4 - 1 = 3\$- \$3 + 0 + 3 = 6\$
In fact, \$6\$ is the maximal sortedness of the permutations of this particular array, and there are 16 permutations of [1,1,2,3,3]
with a sortedness of \$6\$.
[1, 3, 2, 1, 3]
[1, 3, 2, 3, 1]
[1, 3, 2, 1, 3]
[1, 3, 2, 3, 1]
[1, 3, 2, 1, 3]
[1, 3, 2, 3, 1]
[1, 3, 2, 1, 3]
[1, 3, 2, 3, 1]
[3, 1, 2, 1, 3]
[3, 1, 2, 3, 1]
[3, 1, 2, 1, 3]
[3, 1, 2, 3, 1]
[3, 1, 2, 1, 3]
[3, 1, 2, 3, 1]
[3, 1, 2, 1, 3]
[3, 1, 2, 3, 1]
Given a list of positive integers, where each integer appears either once or twice, output a permutation of this list where the sortedness is maximal. You may input and output in any convenient manner, and you may output any number of the permutations with maximal sortedness.
This is code-golf, so the shortest code in bytes wins.
Test cases
input -> output
[1] -> [1]
[8, 7] -> [8, 7]
[1, 1, 2] -> [1, 2, 1]
[9, 7, 4] -> [9, 7, 4]
[2, 9, 3, 10] -> [2, 9, 3, 10]
[4, 4, 10, 10] -> [4, 10, 4, 10]
[1, 1, 2, 3, 3] -> [1, 3, 2, 1, 3]
[2, 8, 5, 6, 5] -> [5, 2, 8, 6, 5]
[5, 2, 6, 1, 9] -> [5, 2, 6, 1, 9]
[7, 1, 1, 4, 5, 5, 8] -> [1, 5, 7, 4, 8, 1, 5]
[3, 1, 2, 8, 3, 10, 8] -> [3, 8, 1, 2, 10, 3, 8]
[1, 1, 2, 2, 3, 3, 4, 4] -> [1, 2, 3, 4, 1, 2, 3, 4]
[4, 4, 3, 3, 2, 2, 1, 1] -> [4, 3, 2, 1, 4, 3, 2, 1]