Best shuffle: Difference between revisions

Content added Content deleted
(→‎{{header|Python}}: Add another algorithm.)
Line 1,209: Line 1,209:


=={{header|Python}}==
=={{header|Python}}==
===Swap if it is locally better algorithm===
<lang python>from collections import Counter

def count(w1,w2):
return sum(c1==c2 for c1,c2 in zip(w1, w2))

def best_shuffle(w):
w2, w2old = list(w), []
n = len(w)
rangew = range(n)
while w2old != w2 and n:
n -= 1
w2old = w2[:]
for i in rangew:
for j in rangew:
if i != j and w2[j] != w2[i] and w[i] != w2[j] and w[j] != w2[i]:
w2[j], w2[i] = w2[i], w2[j]
w2 = ''.join(w2)
return w2, count(w, w2)



if __name__ == '__main__':
test_words = 'tree abracadabra seesaw, elk grrrrrr up a'.split()
for w in 'tree abracadabra seesaw elk grrrrrr up a'.split():
print(w, '->', best_shuffle(w))</lang>

;Sample output
<pre>tree -> ('eert', 0)
abracadabra -> ('baadrbaraac', 0)
seesaw -> ('eswaes', 0)
elk -> ('kel', 0)
grrrrrr -> ('rgrrrrr', 5)
up -> ('pu', 0)
a -> ('a', 1)</pre>

===Alternative algorithm #1===
{{needs-review|Python|This example uses a different algorithm, which is not like the other examples. This algorithm can become stuck near the end of the string. The code now fixes the problem if a "final letter became stuck", but this might or might not fix all inputs.}}
{{needs-review|Python|This example uses a different algorithm, which is not like the other examples. This algorithm can become stuck near the end of the string. The code now fixes the problem if a "final letter became stuck", but this might or might not fix all inputs.}}