Jump to content

Best shuffle: Difference between revisions

(→‎{{header|Groovy}}: added error template)
Line 1,238:
 
=={{header|Groovy}}==
{{incorrect|Groovy|It does not produce best shuffles as defined by task: abracadabra should score zero.}}
<lang groovy>def shuffle(text) {
def listshuffled = (text as List)
for (sourceIndex in 0..<text.size()) {
Collections.shuffle(list)
for (destinationIndex in 0..<text.size()) {
[original: text, shuffled: list.join(""), score: score(text, list)]
if (shuffled[sourceIndex] != shuffled[destinationIndex] && shuffled[sourceIndex] != text[destinationIndex] && shuffled[destinationIndex] != text[sourceIndex]) {
char tmp = shuffled[sourceIndex];
shuffled[sourceIndex] = shuffled[destinationIndex];
shuffled[destinationIndex] = tmp;
best = newTry break;
}
}
best}
[original: text, shuffled: listshuffled.join(""), score: score(text, listshuffled)]
}
 
Line 1,253 ⟶ 1,261:
}
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) {
best = newTry
}
}
best
}
 
["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"].each { text ->
def result = bestShuffleshuffle(text)
println "${result.original}, ${result.shuffled}, (${result.score})"
}</lang>
}
</lang>
Output:
<pre>
abracadabra, bdaarcabaarbaaracadabr, (10)
seesaw, awseseesswea, (0)
elk, kellke, (0)
grrrrrr, rrrrrrgrgrrrrr, (5)
up, pu, (0)
a, a, (1)
Cookies help us deliver our services. By using our services, you agree to our use of cookies.