Best shuffle: Difference between revisions
Content added Content deleted
m (→{{header|J}}) |
(Kotlin version) |
||
Line 1,696: | Line 1,696: | ||
Produced: |
Produced: |
||
⚫ | |||
⚫ | |||
seesaw, ewaess, (0) |
seesaw, ewaess, (0) |
||
elk, lke, (0) |
elk, lke, (0) |
||
grrrrrr, rrrrrgr, (5) |
grrrrrr, rrrrrgr, (5) |
||
up, pu, (0) |
up, pu, (0) |
||
a, a, (1)</ |
a, a, (1)</pre> |
||
=={{header|Kotlin}}== |
|||
From Java. |
|||
<lang scala>package shuffle |
|||
import java.util.Random |
|||
object BestShuffle { |
|||
operator fun invoke(s1: String) : String { |
|||
val s2 = s1.toCharArray() |
|||
shuffle(s2) |
|||
for (i in s2.indices) |
|||
if (s2[i] == s1[i]) |
|||
for (j in s2.indices) |
|||
if (s2[i] != s2[j] && s2[i] != s1[j] && s2[j] != s1[i]) { |
|||
val tmp = s2[i] |
|||
s2[i] = s2[j] |
|||
s2[j] = tmp |
|||
break |
|||
} |
|||
return s1 + ' ' + String(s2) + " (" + count(s1, s2) + ')' |
|||
} |
|||
private fun shuffle(text: CharArray) { |
|||
val rand = Random() |
|||
for (i in text.size - 1 downTo 1) { |
|||
val r = rand.nextInt(i + 1) |
|||
val tmp = text[i] |
|||
text[i] = text[r] |
|||
text[r] = tmp |
|||
} |
|||
} |
|||
private fun count(s1: String, s2: CharArray) : Int { |
|||
var count = 0 |
|||
for (i in s2.indices) |
|||
if (s1[i] == s2[i]) |
|||
count++ |
|||
return count |
|||
} |
|||
} |
|||
fun main(words: Array<String>) = words forEach { println(BestShuffle(it)) }</lang> |
|||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
<lang lb> |
<lang lb>'see Run BASIC solution |
||
'see Run BASIC solution |
|||
list$ = "abracadabra seesaw pop grrrrrr up a" |
list$ = "abracadabra seesaw pop grrrrrr up a" |
||
Line 1,731: | Line 1,772: | ||
next i |
next i |
||
bestShuffle$ = s2$ |
bestShuffle$ = s2$ |
||
end function |
end function</lang> |
||
</lang> |
|||
output |
output |
||
<pre> |
<pre> |