Best shuffle: Difference between revisions
Content added Content deleted
(→{{header|Groovy}}: added error template) |
|||
Line 1,238: | Line 1,238: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
{{incorrect|Groovy|It does not produce best shuffles as defined by task: abracadabra should score zero.}} |
|||
<lang groovy>def shuffle(text) { |
<lang groovy>def shuffle(text) { |
||
def |
def shuffled = (text as List) |
||
for (sourceIndex in 0..<text.size()) { |
|||
Collections.shuffle(list) |
|||
for (destinationIndex in 0..<text.size()) { |
|||
⚫ | |||
if (shuffled[sourceIndex] != shuffled[destinationIndex] && shuffled[sourceIndex] != text[destinationIndex] && shuffled[destinationIndex] != text[sourceIndex]) { |
|||
char tmp = shuffled[sourceIndex]; |
|||
shuffled[sourceIndex] = shuffled[destinationIndex]; |
|||
shuffled[destinationIndex] = tmp; |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
} |
} |
||
Line 1,253: | Line 1,261: | ||
} |
} |
||
score |
score |
||
} |
|||
def bestShuffle(text) { |
|||
def best = shuffle(text) |
|||
for (int i = 0; i < 30 && best.score > 0; i++) { |
|||
def newTry = shuffle(text) |
|||
if (newTry.score < best.score) { |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
} |
} |
||
["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"].each { text -> |
["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"].each { text -> |
||
def result = |
def result = shuffle(text) |
||
println "${result.original}, ${result.shuffled}, (${result.score})" |
println "${result.original}, ${result.shuffled}, (${result.score})" |
||
⚫ | |||
} |
|||
⚫ | |||
Output: |
Output: |
||
<pre> |
<pre> |
||
abracadabra, |
abracadabra, baaracadabr, (0) |
||
seesaw, |
seesaw, esswea, (0) |
||
elk, |
elk, lke, (0) |
||
grrrrrr, |
grrrrrr, rgrrrrr, (5) |
||
up, pu, (0) |
up, pu, (0) |
||
a, a, (1) |
a, a, (1) |