Best shuffle: Difference between revisions

Content added Content deleted
m (→‎{{header|Raku}}: use 'X' to avoid a nested loop)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 33: Line 33:
{{Template:Strings}}
{{Template:Strings}}
<br><br>
<br><br>

=={{header|11l}}==
=={{header|11l}}==
{{trans|Python}}
{{trans|Python}}


<syntaxhighlight lang=11l>F count(w1, wnew)
<syntaxhighlight lang="11l">F count(w1, wnew)
R sum(zip(w1, wnew).map((c1, c2) -> Int(c1 == c2)))
R sum(zip(w1, wnew).map((c1, c2) -> Int(c1 == c2)))


Line 77: Line 76:
abba, baab ,(0)
abba, baab ,(0)
</pre>
</pre>

=={{header|Action!}}==
=={{header|Action!}}==
<syntaxhighlight lang=Action!>PROC BestShuffle(CHAR ARRAY orig,res)
<syntaxhighlight lang="action!">PROC BestShuffle(CHAR ARRAY orig,res)
BYTE i,j,len
BYTE i,j,len
CHAR tmp
CHAR tmp
Line 129: Line 127:
a, a, (1)
a, a, (1)
</pre>
</pre>

=={{header|Ada}}==
=={{header|Ada}}==
{{trans|AWK}}
{{trans|AWK}}
<syntaxhighlight lang=Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded;


Line 190: Line 187:
up, pu, ( 0 )
up, pu, ( 0 )
a, a, ( 1 )</pre>
a, a, ( 1 )</pre>

=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{Trans|Action!}}
{{Trans|Action!}}
<syntaxhighlight lang=algol68>BEGIN # shuffle a string so as many as possible characters are moved #
<syntaxhighlight lang="algol68">BEGIN # shuffle a string so as many as possible characters are moved #
PROC best shuffle = ( STRING orig )STRING:
PROC best shuffle = ( STRING orig )STRING:
BEGIN
BEGIN
Line 234: Line 230:
a, a, (1)
a, a, (1)
</pre>
</pre>

=={{header|Arturo}}==
=={{header|Arturo}}==


<syntaxhighlight lang=rebol>
<syntaxhighlight lang="rebol">
count: function [s1 s2][
count: function [s1 s2][
res: 0
res: 0
Line 286: Line 281:
a -> a | count: 1
a -> a | count: 1
antidisestablishmentarianism -> mesansrntbiissmtailihdaneait | count: 0</pre>
antidisestablishmentarianism -> mesansrntbiissmtailihdaneait | count: 0</pre>

=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<syntaxhighlight lang=AutoHotkey>words := "abracadabra,seesaw,elk,grrrrrr,up,a"
<syntaxhighlight lang="autohotkey">words := "abracadabra,seesaw,elk,grrrrrr,up,a"
Loop Parse, Words,`,
Loop Parse, Words,`,
out .= Score(A_LoopField, Shuffle(A_LoopField))
out .= Score(A_LoopField, Shuffle(A_LoopField))
Line 348: Line 342:
a, a, (1)
a, a, (1)
</pre>
</pre>

=={{header|AWK}}==
=={{header|AWK}}==
{{trans|Icon}}
{{trans|Icon}}
The Icon and Unicon program uses a simple algorithm of swapping. This is relatively easy to translate to Awk.
The Icon and Unicon program uses a simple algorithm of swapping. This is relatively easy to translate to Awk.


<syntaxhighlight lang=awk>{
<syntaxhighlight lang="awk">{
scram = best_shuffle($0)
scram = best_shuffle($0)
print $0 " -> " scram " (" unchanged($0, scram) ")"
print $0 " -> " scram " (" unchanged($0, scram) ")"
Line 407: Line 400:
If those built-in array functions seem strange to you, and if you can understand these for loops, then you might prefer this Awk program. This algorithm counts the letters in the string, sorts the positions, and fills the positions in order.
If those built-in array functions seem strange to you, and if you can understand these for loops, then you might prefer this Awk program. This algorithm counts the letters in the string, sorts the positions, and fills the positions in order.


<syntaxhighlight lang=awk># out["string"] = best shuffle of string _s_
<syntaxhighlight lang="awk"># out["string"] = best shuffle of string _s_
# out["score"] = number of matching characters
# out["score"] = number of matching characters
function best_shuffle(out, s, c, i, j, k, klen, p, pos, set, rlen, slen) {
function best_shuffle(out, s, c, i, j, k, klen, p, pos, set, rlen, slen) {
Line 489: Line 482:
Output:
Output:


<syntaxhighlight lang=bash>$ awk -f best-shuffle.awk
<syntaxhighlight lang="bash">$ awk -f best-shuffle.awk
abracadabra, baarrcadaab, (0)
abracadabra, baarrcadaab, (0)
seesaw, essewa, (0)
seesaw, essewa, (0)
Line 498: Line 491:


The output might change if the <tt>for (c in set)</tt> loop iterates the array in a different order.
The output might change if the <tt>for (c in set)</tt> loop iterates the array in a different order.

=={{header|BaCon}}==
=={{header|BaCon}}==
<syntaxhighlight lang=bacon>DECLARE case$[] = { "tree", "abracadabra", "seesaw", "elk", "grrrrrr", "up", "a" }
<syntaxhighlight lang="bacon">DECLARE case$[] = { "tree", "abracadabra", "seesaw", "elk", "grrrrrr", "up", "a" }


FOR z = 0 TO UBOUND(case$)-1
FOR z = 0 TO UBOUND(case$)-1
Line 528: Line 520:
a:1
a:1
</pre>
</pre>

=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang=bbcbasic> a$ = "abracadabra" : b$ = FNshuffle(a$) : PRINT a$ " -> " b$ FNsame(a$,b$)
<syntaxhighlight lang="bbcbasic"> a$ = "abracadabra" : b$ = FNshuffle(a$) : PRINT a$ " -> " b$ FNsame(a$,b$)
a$ = "seesaw" : b$ = FNshuffle(a$) : PRINT a$ " -> " b$ FNsame(a$,b$)
a$ = "seesaw" : b$ = FNshuffle(a$) : PRINT a$ " -> " b$ FNsame(a$,b$)
a$ = "elk" : b$ = FNshuffle(a$) : PRINT a$ " -> " b$ FNsame(a$,b$)
a$ = "elk" : b$ = FNshuffle(a$) : PRINT a$ " -> " b$ FNsame(a$,b$)
Line 570: Line 561:
a -> a (1)
a -> a (1)
</pre>
</pre>

=={{header|Bracmat}}==
=={{header|Bracmat}}==
Not optimized:
Not optimized:
<syntaxhighlight lang=bracmat>
<syntaxhighlight lang="bracmat">
( shuffle
( shuffle
= m car cdr todo a z count string
= m car cdr todo a z count string
Line 605: Line 595:


Optimized (~100 x faster):
Optimized (~100 x faster):
<syntaxhighlight lang=bracmat>
<syntaxhighlight lang="bracmat">
( shuffle
( shuffle
= m car cdr todo a z count M string tried
= m car cdr todo a z count M string tried
Line 651: Line 641:
{!} Done
{!} Done
</pre>
</pre>

=={{header|C}}==
=={{header|C}}==


Line 658: Line 647:
In essence: we form cyclic groups of character indices where each cyclic group is guaranteed to represent each character only once (two instances of the letter 'a' must have their indices in separate groups), and then we rotate each of the cyclic groups. We then use the before/after version of these cycles to shuffle the original text. The only way a character can be repeated, here, is when a cyclic group contains only one character index, and this can only happen when more than half of the text uses that character. This is C99 code.
In essence: we form cyclic groups of character indices where each cyclic group is guaranteed to represent each character only once (two instances of the letter 'a' must have their indices in separate groups), and then we rotate each of the cyclic groups. We then use the before/after version of these cycles to shuffle the original text. The only way a character can be repeated, here, is when a cyclic group contains only one character index, and this can only happen when more than half of the text uses that character. This is C99 code.


<syntaxhighlight lang=c>#include <stdlib.h>
<syntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
#include <string.h>
#include <string.h>
Line 781: Line 770:


===Version with random result===
===Version with random result===
<syntaxhighlight lang=C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
Line 886: Line 875:
do_string("");
do_string("");
return 0;
return 0;
}</syntaxhighlight>Output<syntaxhighlight lang=text>abracadebra -> edbcarabaar, overlap 0
}</syntaxhighlight>Output<syntaxhighlight lang="text">abracadebra -> edbcarabaar, overlap 0
grrrrrr -> rrgrrrr, overlap 5
grrrrrr -> rrgrrrr, overlap 5
elk -> kel, overlap 0
elk -> kel, overlap 0
Line 893: Line 882:


===Deterministic method===
===Deterministic method===
<syntaxhighlight lang=c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
#include <string.h>


Line 929: Line 918:
return 0;
return 0;
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
For both solutions, a class is used to encapsulate the original string and to scrambling. A private function of the class does the actual sorting. An implicit conversion from string is also provided to allow for simple initialization, e.g.:
For both solutions, a class is used to encapsulate the original string and to scrambling. A private function of the class does the actual sorting. An implicit conversion from string is also provided to allow for simple initialization, e.g.:
<syntaxhighlight lang=csharp>ShuffledString[] array = {"cat", "dog", "mouse"};</syntaxhighlight>
<syntaxhighlight lang="csharp">ShuffledString[] array = {"cat", "dog", "mouse"};</syntaxhighlight>
Which will immediately shuffle each word.
Which will immediately shuffle each word.


A sequential solution, which always produces the same output for the same input.
A sequential solution, which always produces the same output for the same input.
<syntaxhighlight lang=csharp>
<syntaxhighlight lang="csharp">
using System;
using System;
using System.Text;
using System.Text;
Line 1,065: Line 1,053:


And a randomized solution, which will produce a more or less different result on every run:
And a randomized solution, which will produce a more or less different result on every run:
<syntaxhighlight lang=csharp>
<syntaxhighlight lang="csharp">
using System;
using System;
using System.Text;
using System.Text;
Line 1,213: Line 1,201:
a, a, (1)
a, a, (1)
</pre>
</pre>

=={{header|C++}}==
=={{header|C++}}==
{{works with|C++|11}}
{{works with|C++|11}}
{{trans|Java}}
{{trans|Java}}
<syntaxhighlight lang=cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <sstream>
#include <sstream>
#include <algorithm>
#include <algorithm>
Line 1,275: Line 1,262:
a
a
a (1)</pre>
a (1)</pre>

=={{header|Clojure}}==
=={{header|Clojure}}==
Uses same method as J
Uses same method as J


<syntaxhighlight lang=Clojure>(defn score [before after]
<syntaxhighlight lang="clojure">(defn score [before after]
(->> (map = before after)
(->> (map = before after)
(filter true? ,)
(filter true? ,)
Line 1,333: Line 1,319:
["up" "pu" 0]
["up" "pu" 0]
["a" "a" 1]]</syntaxhighlight>
["a" "a" 1]]</syntaxhighlight>

=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<syntaxhighlight lang=lisp>(defun count-equal-chars (string1 string2)
<syntaxhighlight lang="lisp">(defun count-equal-chars (string1 string2)
(loop for c1 across string1 and c2 across string2
(loop for c1 across string1 and c2 across string2
count (char= c1 c2)))
count (char= c1 c2)))
Line 1,367: Line 1,352:


===Version 2===
===Version 2===
<syntaxhighlight lang=lisp>(defun all-best-shuffles (str)
<syntaxhighlight lang="lisp">(defun all-best-shuffles (str)
(let (tbl out (shortest (length str)) (s str))
(let (tbl out (shortest (length str)) (s str))


Line 1,416: Line 1,401:


The output is:
The output is:
<syntaxhighlight lang=lisp>abracadabra: (caardrabaab 0)
<syntaxhighlight lang="lisp">abracadabra: (caardrabaab 0)
seesaw: (ewsase 0)
seesaw: (ewsase 0)
elk: (kel 0)
elk: (kel 0)
Line 1,423: Line 1,408:
a: (a 1)
a: (a 1)
</syntaxhighlight>
</syntaxhighlight>

=={{header|Crystal}}==
=={{header|Crystal}}==
{{trans|Ruby}}
{{trans|Ruby}}


<syntaxhighlight lang=ruby>def best_shuffle(s)
<syntaxhighlight lang="ruby">def best_shuffle(s)
# Fill _pos_ with positions in the order
# Fill _pos_ with positions in the order
# that we want to fill them.
# that we want to fill them.
Line 1,478: Line 1,462:
a, a, (1)
a, a, (1)
</pre>
</pre>

=={{header|D}}==
=={{header|D}}==
===Version with random result===
===Version with random result===
Translation of [[Best_shuffle#Icon_and_Unicon|Icon]] via [[Best_shuffle#AWK|AWK]]
Translation of [[Best_shuffle#Icon_and_Unicon|Icon]] via [[Best_shuffle#AWK|AWK]]
<syntaxhighlight lang=d>import std.stdio, std.random, std.algorithm, std.conv, std.range,
<syntaxhighlight lang="d">import std.stdio, std.random, std.algorithm, std.conv, std.range,
std.traits, std.typecons;
std.traits, std.typecons;


Line 1,525: Line 1,508:


===Deterministic approach===
===Deterministic approach===
<syntaxhighlight lang=d>import std.stdio, std.algorithm, std.range;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;


extern(C) pure nothrow void* alloca(in size_t size);
extern(C) pure nothrow void* alloca(in size_t size);
Line 1,642: Line 1,625:
{{libheader| System.Generics.Collections}}
{{libheader| System.Generics.Collections}}
{{Trans|C#}}
{{Trans|C#}}
<syntaxhighlight lang=Delphi>
<syntaxhighlight lang="delphi">
program Best_shuffle;
program Best_shuffle;


Line 1,784: Line 1,767:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 5.0 :
<syntaxhighlight lang=Elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions;
import extensions'text;
import extensions'text;
Line 1,841: Line 1,824:
The best shuffle of a is a(1)
The best shuffle of a is a(1)
</pre>
</pre>

=={{header|Erlang}}==
=={{header|Erlang}}==
Deterministic version.
Deterministic version.
<syntaxhighlight lang=Erlang>
<syntaxhighlight lang="erlang">
-module( best_shuffle ).
-module( best_shuffle ).


Line 1,894: Line 1,876:
"a" "a" 1
"a" "a" 1
</pre>
</pre>


=={{header|FreeBASIC}}==
{{trans|Liberty BASIC}}
<syntaxhighlight lang=freebasic>
Dim As String*11 lista(6) => {"abracadabra","seesaw","pop","grrrrrr","up","a"}

Function bestShuffle(s1 As String) As String
Dim As String s2 = s1
Dim As Integer i, j, i1, j1
For i = 1 To Len(s2)
For j = 1 To Len(s2)
If (i <> j) And (Mid(s2,i,1) <> Mid(s1,j,1)) And (Mid(s2,j,1) <> Mid(s1,i,1)) Then
If j < i Then i1 = j : j1 = i Else i1 = i : j1 = j
s2 = Left(s2,i1-1) + Mid(s2,j1,1) + Mid(s2,i1+1,(j1-i1)-1) + Mid(s2,i1,1) + Mid(s2,j1+1)
End If
Next j
Next i
bestShuffle = s2
End Function

Dim As String palabra, bs
Dim As Integer puntos
For b As Integer = 0 To Ubound(lista)-1
palabra = lista(b)
bs = bestShuffle(palabra)
puntos = 0
For i As Integer = 1 To Len(palabra)
If Mid(palabra,i,1) = Mid(bs,i,1) Then puntos += 1
Next i
Print palabra; " ==> "; bs; " (puntuaci¢n:"; puntos; ")"
Next b
Sleep
</syntaxhighlight>
{{out}}
<pre>
abracadabra ==> caadrbabaar (puntuación: 0)
seesaw ==> ewaess (puntuación: 0)
pop ==> opp (puntuación: 1)
grrrrrr ==> rgrrrrr (puntuación: 5)
up ==> pu (puntuación: 0)
a ==> a (puntuación: 1)
</pre>

=={{header|Free Pascal}}==
=={{header|Free Pascal}}==
<syntaxhighlight lang=pascal>
<syntaxhighlight lang="pascal">
Program BestShuffle;
Program BestShuffle;


Line 1,996: Line 1,934:
a , a , (1)
a , a , (1)
</pre>
</pre>
=={{header|FreeBASIC}}==
{{trans|Liberty BASIC}}
<syntaxhighlight lang="freebasic">
Dim As String*11 lista(6) => {"abracadabra","seesaw","pop","grrrrrr","up","a"}


Function bestShuffle(s1 As String) As String
Dim As String s2 = s1
Dim As Integer i, j, i1, j1
For i = 1 To Len(s2)
For j = 1 To Len(s2)
If (i <> j) And (Mid(s2,i,1) <> Mid(s1,j,1)) And (Mid(s2,j,1) <> Mid(s1,i,1)) Then
If j < i Then i1 = j : j1 = i Else i1 = i : j1 = j
s2 = Left(s2,i1-1) + Mid(s2,j1,1) + Mid(s2,i1+1,(j1-i1)-1) + Mid(s2,i1,1) + Mid(s2,j1+1)
End If
Next j
Next i
bestShuffle = s2
End Function

Dim As String palabra, bs
Dim As Integer puntos
For b As Integer = 0 To Ubound(lista)-1
palabra = lista(b)
bs = bestShuffle(palabra)
puntos = 0
For i As Integer = 1 To Len(palabra)
If Mid(palabra,i,1) = Mid(bs,i,1) Then puntos += 1
Next i
Print palabra; " ==> "; bs; " (puntuaci¢n:"; puntos; ")"
Next b
Sleep
</syntaxhighlight>
{{out}}
<pre>
abracadabra ==> caadrbabaar (puntuación: 0)
seesaw ==> ewaess (puntuación: 0)
pop ==> opp (puntuación: 1)
grrrrrr ==> rgrrrrr (puntuación: 5)
up ==> pu (puntuación: 0)
a ==> a (puntuación: 1)
</pre>
=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
<syntaxhighlight lang=futurebasic>
<syntaxhighlight lang="futurebasic">


include "Tlbx GameplayKit.incl"
include "Tlbx GameplayKit.incl"
Line 2,074: Line 2,052:
a, a, (1)
a, a, (1)
</pre>
</pre>

=={{header|Go}}==
=={{header|Go}}==
{{trans|Icon and Unicon}}
{{trans|Icon and Unicon}}
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 2,131: Line 2,108:
a -> a (1)
a -> a (1)
</pre>
</pre>

=={{header|Groovy}}==
=={{header|Groovy}}==
<syntaxhighlight lang=groovy>def shuffle(text) {
<syntaxhighlight lang="groovy">def shuffle(text) {
def shuffled = (text as List)
def shuffled = (text as List)
for (sourceIndex in 0..<text.size()) {
for (sourceIndex in 0..<text.size()) {
Line 2,171: Line 2,147:
a, a, (1)
a, a, (1)
</pre>
</pre>

=={{header|Haskell}}==
=={{header|Haskell}}==


We demonstrate several approaches here. In order to test the program we define a testing suite:
We demonstrate several approaches here. In order to test the program we define a testing suite:


<syntaxhighlight lang=Haskell>shufflingQuality l1 l2 = length $ filter id $ zipWith (==) l1 l2
<syntaxhighlight lang="haskell">shufflingQuality l1 l2 = length $ filter id $ zipWith (==) l1 l2


printTest prog = mapM_ test texts
printTest prog = mapM_ test texts
Line 2,193: Line 2,168:
The core of the algorithm is swapping procedure similar to those implemented in AWK and Icon examples. It could be done by a pure program with use of immutable vectors (though it is possible to use mutable vectors living in <tt>ST</tt> or <tt>IO</tt>, but it won't make the program more clear).
The core of the algorithm is swapping procedure similar to those implemented in AWK and Icon examples. It could be done by a pure program with use of immutable vectors (though it is possible to use mutable vectors living in <tt>ST</tt> or <tt>IO</tt>, but it won't make the program more clear).


<syntaxhighlight lang=Haskell>import Data.Vector ((//), (!))
<syntaxhighlight lang="haskell">import Data.Vector ((//), (!))
import qualified Data.Vector as V
import qualified Data.Vector as V
import Data.List (delete, find)
import Data.List (delete, find)
Line 2,228: Line 2,203:
The program works but shuffling is not good in case of a real text, which was just shifted. We can make it better using [[Perfect shuffle]] (faro shuffle) before the swapping procedure.
The program works but shuffling is not good in case of a real text, which was just shifted. We can make it better using [[Perfect shuffle]] (faro shuffle) before the swapping procedure.


<syntaxhighlight lang=Haskell>perfectShuffle :: [a] -> [a]
<syntaxhighlight lang="haskell">perfectShuffle :: [a] -> [a]
perfectShuffle [] = []
perfectShuffle [] = []
perfectShuffle lst | odd n = b : shuffle (zip bs a)
perfectShuffle lst | odd n = b : shuffle (zip bs a)
Line 2,260: Line 2,235:
Additional import:
Additional import:


<syntaxhighlight lang=Haskell>import Control.Monad.Random (getRandomR)</syntaxhighlight>
<syntaxhighlight lang="haskell">import Control.Monad.Random (getRandomR)</syntaxhighlight>


<syntaxhighlight lang=Haskell>randomShuffle :: [a] -> IO [a]
<syntaxhighlight lang="haskell">randomShuffle :: [a] -> IO [a]
randomShuffle [] = return []
randomShuffle [] = return []
randomShuffle lst = do
randomShuffle lst = do
Line 2,291: Line 2,266:
Using streaming technique it is possible to shuffle the sequence on the fly, using relatively small moving window (say of length k) for shuffling procedure. In that case the program will consume constant memory amount O[k] and require O[n*k] operations.
Using streaming technique it is possible to shuffle the sequence on the fly, using relatively small moving window (say of length k) for shuffling procedure. In that case the program will consume constant memory amount O[k] and require O[n*k] operations.


<syntaxhighlight lang=Haskell>{-# LANGUAGE TupleSections, LambdaCase #-}
<syntaxhighlight lang="haskell">{-# LANGUAGE TupleSections, LambdaCase #-}
import Conduit
import Conduit
import Control.Monad.Random (getRandomR)
import Control.Monad.Random (getRandomR)
Line 2,337: Line 2,312:
Additional imports
Additional imports


<syntaxhighlight lang=Haskell>import Data.ByteString.Builder (charUtf8)
<syntaxhighlight lang="haskell">import Data.ByteString.Builder (charUtf8)
import Data.ByteString.Char8 (ByteString, unpack, pack)
import Data.ByteString.Char8 (ByteString, unpack, pack)
import Data.Conduit.ByteString.Builder (builderToByteString)
import Data.Conduit.ByteString.Builder (builderToByteString)
import System.IO (stdin, stdout)</syntaxhighlight>
import System.IO (stdin, stdout)</syntaxhighlight>


<syntaxhighlight lang=Haskell>
<syntaxhighlight lang="haskell">
shuffleBS :: Int -> ByteString -> IO ByteString
shuffleBS :: Int -> ByteString -> IO ByteString
shuffleBS n s =
shuffleBS n s =
Line 2,367: Line 2,342:
$ cat input.txt | ./shuffle
$ cat input.txt | ./shuffle
aeotdR s aoiCtrpmmgi crn theemaysg srioT the tseo.dih psae re isltn ountstoeo tosmaetia es nssimhn ad kaeeinrlataffauytse g oanbs ,e ol e sio ttngdasmw esphut ro ganeemas g alsi arlaeefn,ranifddoii a drnp det r toi ahowgnutan n rgneanppi raohi d oaop blrcst imeioaer ngohrla.eRotn Cst n dce aenletya th8r3 n2ssout1 3dasktaft,rrk9as,a ss iewarf6 d2l ogu asga te g un oa hn4d enaodho(ctt)n, eha laovnsotusw oeinyetsakvn eo ienlrav ygtnu aer. g</pre>
aeotdR s aoiCtrpmmgi crn theemaysg srioT the tseo.dih psae re isltn ountstoeo tosmaetia es nssimhn ad kaeeinrlataffauytse g oanbs ,e ol e sio ttngdasmw esphut ro ganeemas g alsi arlaeefn,ranifddoii a drnp det r toi ahowgnutan n rgneanppi raohi d oaop blrcst imeioaer ngohrla.eRotn Cst n dce aenletya th8r3 n2ssout1 3dasktaft,rrk9as,a ss iewarf6 d2l ogu asga te g un oa hn4d enaodho(ctt)n, eha laovnsotusw oeinyetsakvn eo ienlrav ygtnu aer. g</pre>

=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
The approach taken requires 2n memory and will run in O(n^2) time swapping once per final changed character. The algorithm is concise and conceptually simple avoiding the lists of indices, sorting, cycles, groups, and special cases requiring rotation needed by many of the other solutions. It proceeds through the entire string swapping characters ensuring that neither of the two characters are swapped with another instance of themselves in the ''original'' string.
The approach taken requires 2n memory and will run in O(n^2) time swapping once per final changed character. The algorithm is concise and conceptually simple avoiding the lists of indices, sorting, cycles, groups, and special cases requiring rotation needed by many of the other solutions. It proceeds through the entire string swapping characters ensuring that neither of the two characters are swapped with another instance of themselves in the ''original'' string.


Additionally, this can be trivially modified to randomize the shuffle by uncommenting the line
Additionally, this can be trivially modified to randomize the shuffle by uncommenting the line
<syntaxhighlight lang=icon># every !t :=: ?t # Uncomment to get a random best shuffling</syntaxhighlight> in <tt>bestShuffle</tt>.
<syntaxhighlight lang="icon"># every !t :=: ?t # Uncomment to get a random best shuffling</syntaxhighlight> in <tt>bestShuffle</tt>.
<syntaxhighlight lang=icon>procedure main(args)
<syntaxhighlight lang="icon">procedure main(args)
while scram := bestShuffle(line := read()) do
while scram := bestShuffle(line := read()) do
write(line," -> ",scram," (",unchanged(line,scram),")")
write(line," -> ",scram," (",unchanged(line,scram),")")
Line 2,406: Line 2,380:
->
->
</pre>
</pre>

=={{header|J}}==
=={{header|J}}==


Based on [http://rosettacode.org/mw/index.php?title=Best_shuffle&oldid=97419#J Dan Bron's approach]:
Based on [http://rosettacode.org/mw/index.php?title=Best_shuffle&oldid=97419#J Dan Bron's approach]:


<syntaxhighlight lang=j>bestShuf =: verb define
<syntaxhighlight lang="j">bestShuf =: verb define
yy=. <@({~ ?~@#)@I.@= y
yy=. <@({~ ?~@#)@I.@= y
y C.~ (;yy) </.~ (i.#y) |~ >./#@> yy
y C.~ (;yy) </.~ (i.#y) |~ >./#@> yy
Line 2,426: Line 2,399:
Example:
Example:


<syntaxhighlight lang=j> fmtBest&>;:'abracadabra seesaw elk grrrrrr up a'
<syntaxhighlight lang="j"> fmtBest&>;:'abracadabra seesaw elk grrrrrr up a'
abracadabra, bdacararaab (0)
abracadabra, bdacararaab (0)
seesaw, eawess (0)
seesaw, eawess (0)
Line 2,433: Line 2,406:
up, pu (0)
up, pu (0)
a, a (1)</syntaxhighlight>
a, a (1)</syntaxhighlight>

=={{header|Java}}==
=={{header|Java}}==
Translation of [[Best_shuffle#Icon_and_Unicon|Icon]] via [[Best_shuffle#AWK|AWK]]
Translation of [[Best_shuffle#Icon_and_Unicon|Icon]] via [[Best_shuffle#AWK|AWK]]
<syntaxhighlight lang=java>import java.util.Random;
<syntaxhighlight lang="java">import java.util.Random;


public class BestShuffle {
public class BestShuffle {
Line 2,490: Line 2,462:
up pu (0)
up pu (0)
a a (1)</pre>
a a (1)</pre>

=={{header|JavaScript}}==
=={{header|JavaScript}}==


Based on the J implementation (and this would be a lot more concise if we used something like jQuery):
Based on the J implementation (and this would be a lot more concise if we used something like jQuery):


<syntaxhighlight lang=javascript>function raze(a) { // like .join('') except producing an array instead of a string
<syntaxhighlight lang="javascript">function raze(a) { // like .join('') except producing an array instead of a string
var r= [];
var r= [];
for (var j= 0; j<a.length; j++)
for (var j= 0; j<a.length; j++)
Line 2,545: Line 2,516:
Example:
Example:


<syntaxhighlight lang=html><html><head><title></title></head><body><pre id="out"></pre></body></html>
<syntaxhighlight lang="html"><html><head><title></title></head><body><pre id="out"></pre></body></html>
<script type="text/javascript">
<script type="text/javascript">
/* ABOVE CODE GOES HERE */
/* ABOVE CODE GOES HERE */
Line 2,560: Line 2,531:
up, pu, (0)
up, pu, (0)
a, a, (1)</pre>
a, a, (1)</pre>

=={{header|jq}}==
=={{header|jq}}==
{{works with|jq|1.5}}
{{works with|jq|1.5}}
The implementation in this section uses the deterministic "swap" algorithm found in other entries on this page.
The implementation in this section uses the deterministic "swap" algorithm found in other entries on this page.


<syntaxhighlight lang=jq>def count(s): reduce s as $i (0;.+1);
<syntaxhighlight lang="jq">def count(s): reduce s as $i (0;.+1);


def swap($i;$j):
def swap($i;$j):
Line 2,601: Line 2,571:


'''Examples:'''
'''Examples:'''
<syntaxhighlight lang=jq>"abracadabra", "seesaw", "elk", "grrrrrr", "up", "a", "antidisestablishmentarianism"
<syntaxhighlight lang="jq">"abracadabra", "seesaw", "elk", "grrrrrr", "up", "a", "antidisestablishmentarianism"
| bestShuffle</syntaxhighlight>
| bestShuffle</syntaxhighlight>


Line 2,613: Line 2,583:
a, a, (1)
a, a, (1)
antidisestablishmentarianism, maaaadisesitblishmenttrninis, (0)</pre>
antidisestablishmentarianism, maaaadisesitblishmenttrninis, (0)</pre>

=={{header|Julia}}==
=={{header|Julia}}==
{{trans|Python}}
{{trans|Python}}
<syntaxhighlight lang=julia># v0.6
<syntaxhighlight lang="julia"># v0.6


function bestshuffle(str::String)::Tuple{String,Int}
function bestshuffle(str::String)::Tuple{String,Int}
Line 2,676: Line 2,645:
up: pu (0)
up: pu (0)
a: a (1)</pre>
a: a (1)</pre>

=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Java}}
{{trans|Java}}
<syntaxhighlight lang=scala>import java.util.Random
<syntaxhighlight lang="scala">import java.util.Random


object BestShuffle {
object BestShuffle {
Line 2,724: Line 2,692:
up pu (0)
up pu (0)
a a (1)</pre>
a a (1)</pre>

=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang=lb>'see Run BASIC solution
<syntaxhighlight lang="lb">'see Run BASIC solution
list$ = "abracadabra seesaw pop grrrrrr up a"
list$ = "abracadabra seesaw pop grrrrrr up a"


Line 2,760: Line 2,727:
up pu 0
up pu 0
a a 1</pre>
a a 1</pre>


=={{header|Lua}}==
=={{header|Lua}}==
<syntaxhighlight lang=lua>math.randomseed(os.time())
<syntaxhighlight lang="lua">math.randomseed(os.time())


local function shuffle(t)
local function shuffle(t)
Line 2,820: Line 2,785:
up, pu, (0)
up, pu, (0)
a, a, (1)</pre>
a, a, (1)</pre>

=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica>BestShuffle[data_] :=
<syntaxhighlight lang="mathematica">BestShuffle[data_] :=
Flatten[{data,First[SortBy[
Flatten[{data,First[SortBy[
List[#, StringLength[data]-HammingDistance[#,data]] & /@ StringJoin /@ Permutations[StringSplit[data, ""]], Last]]}]
List[#, StringLength[data]-HammingDistance[#,data]] & /@ StringJoin /@ Permutations[StringSplit[data, ""]], Last]]}]
Line 2,836: Line 2,800:
up, pu,(0)
up, pu,(0)
a, a,(1)</pre>
a, a,(1)</pre>

=={{header|Nim}}==
=={{header|Nim}}==
{{trans|Java}}
{{trans|Java}}
<syntaxhighlight lang=Nim>import times
<syntaxhighlight lang="nim">import times
import sequtils
import sequtils
import strutils
import strutils
Line 2,884: Line 2,847:
a a 1
a a 1
antidisestablishmentarianism mietnshieistrlaatbsdsnaiinma 0</pre>
antidisestablishmentarianism mietnshieistrlaatbsdsnaiinma 0</pre>

=={{header|OCaml}}==
=={{header|OCaml}}==


Deterministic
Deterministic


<syntaxhighlight lang=ocaml>let best_shuffle s =
<syntaxhighlight lang="ocaml">let best_shuffle s =
let len = String.length s in
let len = String.length s in
let r = String.copy s in
let r = String.copy s in
Line 2,937: Line 2,899:
'up', 'pu' -> 0
'up', 'pu' -> 0
'a', 'a' -> 1</pre>
'a', 'a' -> 1</pre>

=={{header|Pascal}}==
=={{header|Pascal}}==
{{works with|Free_Pascal}}
{{works with|Free_Pascal}}
<syntaxhighlight lang=pascal>program BestShuffleDemo(output);
<syntaxhighlight lang="pascal">program BestShuffleDemo(output);
function BestShuffle(s: string): string;
function BestShuffle(s: string): string;
Line 2,988: Line 2,949:
up, pu, (0)
up, pu, (0)
a, a, (1)</pre>
a, a, (1)</pre>

=={{header|Perl}}==
=={{header|Perl}}==
The Algorithm::Permute module does not ship with perl, but is freely available from CPAN.
The Algorithm::Permute module does not ship with perl, but is freely available from CPAN.


<syntaxhighlight lang=perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;
use List::Util qw(shuffle);
use List::Util qw(shuffle);
Line 3,048: Line 3,008:


{{trans|go}}
{{trans|go}}
<syntaxhighlight lang=perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;
use List::Util qw(shuffle);
use List::Util qw(shuffle);
Line 3,079: Line 3,039:
The output has the same format as the first perl implementation,
The output has the same format as the first perl implementation,
but only takes quadratic time per word.
but only takes quadratic time per word.

=={{header|Phix}}==
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"abracadabra"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"seesaw"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"elk"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"grrrrrr"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"up"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"a"</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"abracadabra"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"seesaw"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"elk"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"grrrrrr"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"up"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"a"</span><span style="color: #0000FF;">}</span>
Line 3,118: Line 3,077:
a -> a (1)
a -> a (1)
</pre>
</pre>

=={{header|PHP}}==
=={{header|PHP}}==
Translation of [[Best_shuffle#Icon_and_Unicon|Icon]] via [[Best_shuffle#AWK|AWK]]
Translation of [[Best_shuffle#Icon_and_Unicon|Icon]] via [[Best_shuffle#AWK|AWK]]
<syntaxhighlight lang=php>foreach (split(' ', 'abracadabra seesaw pop grrrrrr up a') as $w)
<syntaxhighlight lang="php">foreach (split(' ', 'abracadabra seesaw pop grrrrrr up a') as $w)
echo bestShuffle($w) . '<br>';
echo bestShuffle($w) . '<br>';


Line 3,154: Line 3,112:
up pu (0)
up pu (0)
a a (1)</pre>
a a (1)</pre>

=={{header|Picat}}==
=={{header|Picat}}==
Using a CP (Constraint Programming) solver guarantees an optimal solution. This is deterministic since the solve heuristic ("split") always give the same first result.
Using a CP (Constraint Programming) solver guarantees an optimal solution. This is deterministic since the solve heuristic ("split") always give the same first result.


<syntaxhighlight lang=Picat>import cp.
<syntaxhighlight lang="picat">import cp.


go =>
go =>
Line 3,235: Line 3,192:
===All optimal solutions===
===All optimal solutions===
Using a constraint solver makes it quite easy to generate all optimal solutions.
Using a constraint solver makes it quite easy to generate all optimal solutions.
<syntaxhighlight lang=Picat>go2 ?=>
<syntaxhighlight lang="picat">go2 ?=>
Words = ["abracadabra",
Words = ["abracadabra",
"seesaw",
"seesaw",
Line 3,307: Line 3,264:
num_solutions = 1
num_solutions = 1
solutions = [aaaaaaa]</pre>
solutions = [aaaaaaa]</pre>

=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp>(de bestShuffle (Str)
<syntaxhighlight lang="picolisp">(de bestShuffle (Str)
(let Lst NIL
(let Lst NIL
(for C (setq Str (chop Str))
(for C (setq Str (chop Str))
Line 3,341: Line 3,297:
: (bestShuffle "a")
: (bestShuffle "a")
a a (1)</pre>
a a (1)</pre>

=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang=pli>shuffle: procedure options (main); /* 14/1/2011 */
<syntaxhighlight lang="pli">shuffle: procedure options (main); /* 14/1/2011 */
declare (s, saves) character (20) varying, c character (1);
declare (s, saves) character (20) varying, c character (1);
declare t(length(s)) bit (1);
declare t(length(s)) bit (1);
Line 3,411: Line 3,366:
A 1
A 1
</pre>
</pre>

=={{header|PowerShell}}==
=={{header|PowerShell}}==
{{works with|PowerShell|3}}
{{works with|PowerShell|3}}
<syntaxhighlight lang=PowerShell># Calculate best possible shuffle score for a given string
<syntaxhighlight lang="powershell"># Calculate best possible shuffle score for a given string
# (Split out into separate function so we can use it separately in our output)
# (Split out into separate function so we can use it separately in our output)
function Get-BestScore ( [string]$String )
function Get-BestScore ( [string]$String )
Line 3,466: Line 3,420:
return $Shuffle
return $Shuffle
}</syntaxhighlight>
}</syntaxhighlight>
<syntaxhighlight lang=PowerShell>ForEach ( $String in ( 'abracadabra', 'seesaw', 'elk', 'grrrrrr', 'up', 'a' ) )
<syntaxhighlight lang="powershell">ForEach ( $String in ( 'abracadabra', 'seesaw', 'elk', 'grrrrrr', 'up', 'a' ) )
{
{
$Shuffle = Get-BestShuffle $String
$Shuffle = Get-BestShuffle $String
Line 3,479: Line 3,433:
up, pu, (0)
up, pu, (0)
a, a, (1)</pre>
a, a, (1)</pre>

=={{header|Prolog}}==
=={{header|Prolog}}==
Works with SWI-Prolog
Works with SWI-Prolog
<syntaxhighlight lang=Prolog>:- dynamic score/2.
<syntaxhighlight lang="prolog">:- dynamic score/2.


best_shuffle :-
best_shuffle :-
Line 3,570: Line 3,523:
===Version with random result===
===Version with random result===
====solution====
====solution====
<syntaxhighlight lang=Prolog>
<syntaxhighlight lang="prolog">
:- system:set_prolog_flag(double_quotes,codes) .
:- system:set_prolog_flag(double_quotes,codes) .


Line 3,691: Line 3,644:
*/
*/
</pre>
</pre>

=={{header|PureBasic}}==
=={{header|PureBasic}}==
This solution creates cycles of letters of letters that are then rotated to produce the final maximal shuffle. It includes an extra sort step that ensures the original string to be returned if it is repeatedly shuffled.
This solution creates cycles of letters of letters that are then rotated to produce the final maximal shuffle. It includes an extra sort step that ensures the original string to be returned if it is repeatedly shuffled.
<syntaxhighlight lang=PureBasic>Structure charInfo
<syntaxhighlight lang="purebasic">Structure charInfo
Char.s
Char.s
List Position.i()
List Position.i()
Line 3,811: Line 3,763:
up, pu, (0)
up, pu, (0)
a, a, (1)</pre>
a, a, (1)</pre>

=={{header|Python}}==
=={{header|Python}}==
===Swap if it is locally better algorithm===
===Swap if it is locally better algorithm===
With added randomization of swaps!
With added randomization of swaps!
<syntaxhighlight lang=python>import random
<syntaxhighlight lang="python">import random


def count(w1,wnew):
def count(w1,wnew):
Line 3,878: Line 3,829:
===Alternative algorithm #1===
===Alternative algorithm #1===


<syntaxhighlight lang=python>#!/usr/bin/env python
<syntaxhighlight lang="python">#!/usr/bin/env python


def best_shuffle(s):
def best_shuffle(s):
Line 3,935: Line 3,886:
up, pu, (0)
up, pu, (0)
a, a, (1)</pre>
a, a, (1)</pre>

=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang=Racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 3,968: Line 3,918:
a, a, (1)
a, a, (1)
</pre>
</pre>

=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
{{trans|Sidef}}
{{trans|Sidef}}


<syntaxhighlight lang=raku line>sub best-shuffle(Str $orig) {
<syntaxhighlight lang="raku line">sub best-shuffle(Str $orig) {
my @s = $orig.comb;
my @s = $orig.comb;
my @t = @s.pick(*);
my @t = @s.pick(*);
Line 3,999: Line 3,948:
up, pu, (0)
up, pu, (0)
a, a, (1)</pre>
a, a, (1)</pre>

=={{header|Rascal}}==
=={{header|Rascal}}==
{{incomplete|Rascal|No output given.}}
{{incomplete|Rascal|No output given.}}
<syntaxhighlight lang=Rascal>import Prelude;
<syntaxhighlight lang="rascal">import Prelude;


public tuple[str, str, int] bestShuffle(str s){
public tuple[str, str, int] bestShuffle(str s){
Line 4,015: Line 3,963:
return (0 | it + 1 | n <- index(characters), permutations[n] == characters[n]);
return (0 | it + 1 | n <- index(characters), permutations[n] == characters[n]);
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|REXX}}==
=={{header|REXX}}==
<syntaxhighlight lang=rexx>/*REXX program determines and displays the best shuffle for any list of words or tokens.*/
<syntaxhighlight lang="rexx">/*REXX program determines and displays the best shuffle for any list of words or tokens.*/
parse arg $ /*get some words from the command line.*/
parse arg $ /*get some words from the command line.*/
if $='' then $= 'tree abracadabra seesaw elk grrrrrr up a' /*use the defaults?*/
if $='' then $= 'tree abracadabra seesaw elk grrrrrr up a' /*use the defaults?*/
Line 4,057: Line 4,004:
original: a new: a score: 1
original: a new: a score: 1
</pre>
</pre>

=={{header|Ring}}==
=={{header|Ring}}==
<syntaxhighlight lang=ring>
<syntaxhighlight lang="ring">
# Project : Best shuffle
# Project : Best shuffle


Line 4,103: Line 4,049:
a -> a 1
a -> a 1
</pre>
</pre>

=={{header|Ruby}}==
=={{header|Ruby}}==
{{works with|Ruby|1.9}}
{{works with|Ruby|1.9}}
{{trans|Raku}}
{{trans|Raku}}


<syntaxhighlight lang=ruby>def best_shuffle(s)
<syntaxhighlight lang="ruby">def best_shuffle(s)
# Fill _pos_ with positions in the order
# Fill _pos_ with positions in the order
# that we want to fill them.
# that we want to fill them.
Line 4,154: Line 4,099:
a, a, (1)
a, a, (1)
</pre>
</pre>

=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<syntaxhighlight lang=runbasic>list$ = "abracadabra seesaw pop grrrrrr up a"
<syntaxhighlight lang="runbasic">list$ = "abracadabra seesaw pop grrrrrr up a"


while word$(list$,ii + 1," ") <> ""
while word$(list$,ii + 1," ") <> ""
Line 4,190: Line 4,134:
up pu 0
up pu 0
a a 1</pre>
a a 1</pre>

=={{header|Rust}}==
=={{header|Rust}}==
{{libheader|rand}}
{{libheader|rand}}
<syntaxhighlight lang=rust>extern crate permutohedron;
<syntaxhighlight lang="rust">extern crate permutohedron;
extern crate rand;
extern crate rand;


Line 4,338: Line 4,281:
a, a, (1)
a, a, (1)
</pre>
</pre>

=={{header|Scala}}==
=={{header|Scala}}==
There are two implementations. One is simple but exponential and very inefficient. The second one is quadratic. Both are pure functional. Given quadratic solution has a bigger constant than the one used in the Python implementation, but doesn't use mutable datastructures.
There are two implementations. One is simple but exponential and very inefficient. The second one is quadratic. Both are pure functional. Given quadratic solution has a bigger constant than the one used in the Python implementation, but doesn't use mutable datastructures.
<syntaxhighlight lang=scala>
<syntaxhighlight lang="scala">
def coincidients(s1: Seq[Char], s2: Seq[Char]): Int = (s1, s2).zipped.count(p => (p._1 == p._2))
def coincidients(s1: Seq[Char], s2: Seq[Char]): Int = (s1, s2).zipped.count(p => (p._1 == p._2))
def freqMap(s1: List[Char]) = s1.groupBy(_.toChar).mapValues(_.size)
def freqMap(s1: List[Char]) = s1.groupBy(_.toChar).mapValues(_.size)
Line 4,378: Line 4,320:
</syntaxhighlight>
</syntaxhighlight>
The test code:
The test code:
<syntaxhighlight lang=scala>
<syntaxhighlight lang="scala">
def main(args: Array[String]): Unit = {
def main(args: Array[String]): Unit = {
println(bestShuffle("abracadabra"));
println(bestShuffle("abracadabra"));
Line 4,400: Line 4,342:
</pre>
</pre>
The ScalaCheck code
The ScalaCheck code
<syntaxhighlight lang=scala>
<syntaxhighlight lang="scala">
object BestShuffleSpecification extends Properties("BestShuffle") {
object BestShuffleSpecification extends Properties("BestShuffle") {


Line 4,420: Line 4,362:
}
}
</syntaxhighlight>
</syntaxhighlight>

=={{header|Scheme}}==
=={{header|Scheme}}==
<syntaxhighlight lang=scheme>
<syntaxhighlight lang="scheme">
(define count
(define count
(lambda (str1 str2)
(lambda (str1 str2)
Line 4,499: Line 4,440:
a a (1)
a a (1)
</pre>
</pre>

=={{header|Seed7}}==
=={{header|Seed7}}==
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const func string: bestShuffle (in string: stri) is func
const func string: bestShuffle (in string: stri) is func
Line 4,552: Line 4,492:
a, a, (1)
a, a, (1)
</pre>
</pre>

=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Go}}
{{trans|Go}}
<syntaxhighlight lang=ruby>func best_shuffle(String orig) -> (String, Number) {
<syntaxhighlight lang="ruby">func best_shuffle(String orig) -> (String, Number) {


var s = orig.chars
var s = orig.chars
Line 4,583: Line 4,522:
up pu: 0
up pu: 0
a a: 1</pre>
a a: 1</pre>

=={{header|Tcl}}==
=={{header|Tcl}}==
{{tcllib|struct::list}}
{{tcllib|struct::list}}
<syntaxhighlight lang=tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5
package require struct::list
package require struct::list


Line 4,608: Line 4,546:
}</syntaxhighlight>
}</syntaxhighlight>
Demonstration:
Demonstration:
<syntaxhighlight lang=tcl>foreach sample {abracadabra seesaw elk grrrrrr up a} {
<syntaxhighlight lang="tcl">foreach sample {abracadabra seesaw elk grrrrrr up a} {
puts [bestshuffle $sample]
puts [bestshuffle $sample]
}</syntaxhighlight>
}</syntaxhighlight>
Line 4,620: Line 4,558:
a,a,(1)
a,a,(1)
</pre>
</pre>

=={{header|Ursala}}==
=={{header|Ursala}}==
An implementation based on the J solution looks like this.
An implementation based on the J solution looks like this.
<syntaxhighlight lang=Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import nat
#import nat


Line 4,634: Line 4,571:
main = ~&LS <.~&l,@r :/` ,' ('--+ --')'+ ~&h+ %nP+ length@plrEF>^(~&,shuffle)* words</syntaxhighlight>
main = ~&LS <.~&l,@r :/` ,' ('--+ --')'+ ~&h+ %nP+ length@plrEF>^(~&,shuffle)* words</syntaxhighlight>
A solution based on exponential search would use this definition of <code>shuffle</code> (cf. Haskell and Tcl).
A solution based on exponential search would use this definition of <code>shuffle</code> (cf. Haskell and Tcl).
<syntaxhighlight lang=Ursala>shuffle = ~&r+ length@plrEZF$^^D/~& permutations</syntaxhighlight>
<syntaxhighlight lang="ursala">shuffle = ~&r+ length@plrEZF$^^D/~& permutations</syntaxhighlight>
output:
output:
<pre>abracadabra caarrbabaad (0)
<pre>abracadabra caarrbabaad (0)
Line 4,642: Line 4,579:
up pu (0)
up pu (0)
a a (1)</pre>
a a (1)</pre>

=={{header|VBA}}==
=={{header|VBA}}==


<syntaxhighlight lang=vb>
<syntaxhighlight lang="vb">
Option Explicit
Option Explicit


Line 4,750: Line 4,686:
qwerty ==> eytwrq (Score : 0)
qwerty ==> eytwrq (Score : 0)
tttt ==> tttt (Score : 4)</pre>
tttt ==> tttt (Score : 4)</pre>

=={{header|VBScript}}==
=={{header|VBScript}}==
{{trans|Java}}
{{trans|Java}}
<syntaxhighlight lang=vb>'Best Shuffle Task
<syntaxhighlight lang="vb">'Best Shuffle Task
'VBScript Implementation
'VBScript Implementation


Line 4,813: Line 4,748:
up,pu,(0)
up,pu,(0)
a,a,(1)</pre>
a,a,(1)</pre>

=={{header|Wren}}==
=={{header|Wren}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<syntaxhighlight lang=ecmascript>import "random" for Random
<syntaxhighlight lang="ecmascript">import "random" for Random


class BestShuffle {
class BestShuffle {
Line 4,869: Line 4,803:
a, a, (1)
a, a, (1)
</pre>
</pre>

=={{header|XPL0}}==
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0>include c:\cxpl\codes; \'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \'code' declarations
string 0; \use zero-terminated string convention
string 0; \use zero-terminated string convention


Line 4,916: Line 4,849:
a, a, (1)
a, a, (1)
</pre>
</pre>

=={{header|zkl}}==
=={{header|zkl}}==
{{trans|D}}
{{trans|D}}
{{trans|Common Lisp}}
{{trans|Common Lisp}}
<syntaxhighlight lang=zkl>fcn bestShuffle(str){
<syntaxhighlight lang="zkl">fcn bestShuffle(str){
s:=str.split("").shuffle(); // -->List
s:=str.split("").shuffle(); // -->List
if(not s) return(str,str.len()); // can't shuffle "" or "a"
if(not s) return(str,str.len()); // can't shuffle "" or "a"
Line 4,935: Line 4,867:
return(s.concat(), s.zipWith('==,str).sum(0));
return(s.concat(), s.zipWith('==,str).sum(0));
}</syntaxhighlight>
}</syntaxhighlight>
<syntaxhighlight lang=zkl>ss:=T("abracadabra","immediately","grrrrrr","seesaw","pop","up","a","");
<syntaxhighlight lang="zkl">ss:=T("abracadabra","immediately","grrrrrr","seesaw","pop","up","a","");
foreach s in (ss){
foreach s in (ss){
ns,cnt:=bestShuffle(s);
ns,cnt:=bestShuffle(s);
Line 4,951: Line 4,883:
--> (0)
--> (0)
</pre>
</pre>

=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
{{trans|AWK}}
{{trans|AWK}}
<syntaxhighlight lang=zxbasic>10 FOR n=1 TO 6
<syntaxhighlight lang="zxbasic">10 FOR n=1 TO 6
20 READ w$
20 READ w$
30 GO SUB 1000
30 GO SUB 1000
Line 4,981: Line 4,912:
up pu 0
up pu 0
a a 1</pre>
a a 1</pre>

{{omit from|bc|No string operations.}}
{{omit from|bc|No string operations.}}
{{omit from|dc|No string operations.}}
{{omit from|dc|No string operations.}}