Best shuffle: Difference between revisions

m
syntax highlighting fixup automation
mNo edit summary
m (syntax highlighting fixup automation)
Line 37:
{{trans|Python}}
 
<langsyntaxhighlight lang=11l>F count(w1, wnew)
R sum(zip(w1, wnew).map((c1, c2) -> Int(c1 == c2)))
 
Line 60:
L(w) test_words
V (wnew, c) = best_shuffle(w)
print(‘#29, #<29 ,(#.)’.format(w, wnew, c))</langsyntaxhighlight>
 
{{out}}
Line 79:
 
=={{header|Action!}}==
<langsyntaxhighlight lang=Action!>PROC BestShuffle(CHAR ARRAY orig,res)
BYTE i,j,len
CHAR tmp
Line 118:
Test("up")
Test("a")
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Best_shuffle.png Screenshot from Atari 8-bit computer]
Line 132:
=={{header|Ada}}==
{{trans|AWK}}
<langsyntaxhighlight lang=Ada>with Ada.Text_IO;
with Ada.Strings.Unbounded;
 
Line 181:
end;
end loop;
end Best_Shuffle;</langsyntaxhighlight>
 
Output:
Line 193:
=={{header|ALGOL 68}}==
{{Trans|Action!}}
<langsyntaxhighlight lang=algol68>BEGIN # shuffle a string so as many as possible characters are moved #
PROC best shuffle = ( STRING orig )STRING:
BEGIN
Line 224:
test( "up" );
test( "a" )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 237:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang=rebol>
count: function [s1 s2][
res: 0
Line 275:
sf: bestShuffle w
print [w "->" sf "| count:" count w sf]
]</langsyntaxhighlight>
 
{{out}}
Line 288:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang=AutoHotkey>words := "abracadabra,seesaw,elk,grrrrrr,up,a"
Loop Parse, Words,`,
out .= Score(A_LoopField, Shuffle(A_LoopField))
Line 339:
r++
return a ", " b ", (" r ")`n"
}</langsyntaxhighlight>
Output:
<pre>abracadabra, caadarrbaab, (0)
Line 353:
The Icon and Unicon program uses a simple algorithm of swapping. This is relatively easy to translate to Awk.
 
<langsyntaxhighlight lang=awk>{
scram = best_shuffle($0)
print $0 " -> " scram " (" unchanged($0, scram) ")"
Line 392:
}
return count
}</langsyntaxhighlight>
 
This program has the same output as the Icon and Unicon program.
Line 407:
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.
 
<langsyntaxhighlight lang=awk># out["string"] = best shuffle of string _s_
# out["score"] = number of matching characters
function best_shuffle(out, s, c, i, j, k, klen, p, pos, set, rlen, slen) {
Line 485:
words[i], result["string"], result["score"]
}
}</langsyntaxhighlight>
 
Output:
 
<langsyntaxhighlight lang=bash>$ awk -f best-shuffle.awk
abracadabra, baarrcadaab, (0)
seesaw, essewa, (0)
Line 495:
grrrrrr, rgrrrrr, (5)
up, pu, (0)
a, a, (1)</langsyntaxhighlight>
 
The output might change if the <tt>for (c in set)</tt> loop iterates the array in a different order.
 
=={{header|BaCon}}==
<langsyntaxhighlight lang=bacon>DECLARE case$[] = { "tree", "abracadabra", "seesaw", "elk", "grrrrrr", "up", "a" }
 
FOR z = 0 TO UBOUND(case$)-1
Line 517:
 
PRINT MERGE$(result$), ":", total
NEXT</langsyntaxhighlight>
{{output}}
<pre>
Line 531:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight 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$ = "elk" : b$ = FNshuffle(a$) : PRINT a$ " -> " b$ FNsame(a$,b$)
Line 560:
IF MID$(s$,i%,1)=MID$(t$,i%,1) n% += 1
NEXT
= " (" + STR$(n%) + ")"</langsyntaxhighlight>
Output (varies between runs):
<pre>
Line 573:
=={{header|Bracmat}}==
Not optimized:
<langsyntaxhighlight lang=bracmat>
( shuffle
= m car cdr todo a z count string
Line 602:
)
& Done
</syntaxhighlight>
</lang>
 
Optimized (~100 x faster):
<langsyntaxhighlight lang=bracmat>
( shuffle
= m car cdr todo a z count M string tried
Line 640:
)
& Done
</syntaxhighlight>
</lang>
Output:
<pre>
Line 658:
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.
 
<langsyntaxhighlight lang=c>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
Line 768:
 
return EXIT_SUCCESS;
}</langsyntaxhighlight>
Output:
<pre>abracadabra, brabacadaar, (0)
Line 781:
 
===Version with random result===
<langsyntaxhighlight lang=C>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 886:
do_string("");
return 0;
}</langsyntaxhighlight>Output<syntaxhighlight lang=text>abracadebra -> edbcarabaar, overlap 0
grrrrrr -> rrgrrrr, overlap 5
elk -> kel, overlap 0
seesaw -> ewsesa, overlap 0
-> , overlap 0</langsyntaxhighlight>
 
===Deterministic method===
<langsyntaxhighlight lang=c>#include <stdio.h>
#include <string.h>
 
Line 928:
}
return 0;
}</langsyntaxhighlight>
 
=={{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.:
<langsyntaxhighlight lang=csharp>ShuffledString[] array = {"cat", "dog", "mouse"};</langsyntaxhighlight>
Which will immediately shuffle each word.
 
A sequential solution, which always produces the same output for the same input.
<langsyntaxhighlight lang=csharp>
using System;
using System.Text;
Line 1,062:
}
}
</syntaxhighlight>
</lang>
 
And a randomized solution, which will produce a more or less different result on every run:
<langsyntaxhighlight lang=csharp>
using System;
using System.Text;
Line 1,191:
}
}
</syntaxhighlight>
</lang>
 
A sample output for the sequential shuffle:
Line 1,217:
{{works with|C++|11}}
{{trans|Java}}
<langsyntaxhighlight lang=cpp>#include <iostream>
#include <sstream>
#include <algorithm>
Line 1,261:
cout << bs(basic_string<char>(arguments[i])) << endl;
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>abracadabra
Line 1,279:
Uses same method as J
 
<langsyntaxhighlight lang=Clojure>(defn score [before after]
(->> (map = before after)
(filter true? ,)
Line 1,332:
["grrrrrr" "rgrrrrr" 5]
["up" "pu" 0]
["a" "a" 1]]</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang=lisp>(defun count-equal-chars (string1 string2)
(loop for c1 across string1 and c2 across string2
count (char= c1 c2)))
Line 1,357:
(count-equal-chars string shuffled)))))
 
(best-shuffle '("abracadabra" "seesaw" "elk" "grrrrrr" "up" "a"))</langsyntaxhighlight>
Output:
abracadabra caadrbabaar (0)
Line 1,367:
 
===Version 2===
<langsyntaxhighlight lang=lisp>(defun all-best-shuffles (str)
(let (tbl out (shortest (length str)) (s str))
 
Line 1,413:
(dolist (s (list "abracadabra" "seesaw" "elk" "grrrrrr" "up" "a"))
(format t "~A: ~A~%" s (best-shuffle s)))
</syntaxhighlight>
</lang>
 
The output is:
<langsyntaxhighlight lang=lisp>abracadabra: (caardrabaab 0)
seesaw: (ewsase 0)
elk: (kel 0)
Line 1,422:
up: (pu 0)
a: (a 1)
</syntaxhighlight>
</lang>
 
=={{header|Crystal}}==
{{trans|Ruby}}
 
<langsyntaxhighlight lang=ruby>def best_shuffle(s)
# Fill _pos_ with positions in the order
# that we want to fill them.
Line 1,467:
new, score = best_shuffle(word)
puts "%s, %s, (%d)" % [word, new, score]
end</langsyntaxhighlight>
 
{{out}}
Line 1,482:
===Version with random result===
Translation of [[Best_shuffle#Icon_and_Unicon|Icon]] via [[Best_shuffle#AWK|AWK]]
<langsyntaxhighlight lang=d>import std.stdio, std.random, std.algorithm, std.conv, std.range,
std.traits, std.typecons;
 
Line 1,522:
writefln("%s : %s (%d)", entry, res[]);
}
}</langsyntaxhighlight>
 
===Deterministic approach===
<langsyntaxhighlight lang=d>import std.stdio, std.algorithm, std.range;
 
extern(C) pure nothrow void* alloca(in size_t size);
Line 1,627:
writefln("%s, %s, (%d)", txt, result, nEqual);
}
}</langsyntaxhighlight>
{{out}}
<pre>abracadabra, brabacadaar, (0)
Line 1,642:
{{libheader| System.Generics.Collections}}
{{Trans|C#}}
<langsyntaxhighlight lang=Delphi>
program Best_shuffle;
 
Line 1,781:
Readln;
end.
</syntaxhighlight>
</lang>
=={{header|Elena}}==
ELENA 5.0 :
<langsyntaxhighlight lang=Elena>import system'routines;
import extensions;
import extensions'text;
Line 1,831:
 
console.readChar()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,844:
=={{header|Erlang}}==
Deterministic version.
<langsyntaxhighlight lang=Erlang>
-module( best_shuffle ).
 
Line 1,883:
{_First_reversed_original, [Character_acc | First_part_acc]} = lists:unzip( First_reversed_zip ),
[Character_acc | Last_part_acc] ++ [Last_character_acc | First_part_acc].
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,898:
=={{header|FreeBASIC}}==
{{trans|Liberty BASIC}}
<langsyntaxhighlight lang=freebasic>
Dim As String*11 lista(6) => {"abracadabra","seesaw","pop","grrrrrr","up","a"}
 
Line 1,927:
Next b
Sleep
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,939:
 
=={{header|Free Pascal}}==
<langsyntaxhighlight lang=pascal>
Program BestShuffle;
 
Line 1,986:
End.
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,998:
 
=={{header|FutureBasic}}==
<langsyntaxhighlight lang=futurebasic>
 
include "Tlbx GameplayKit.incl"
Line 2,043:
 
HandleEvents
</syntaxhighlight>
</lang>
Output with four shuffles:
<pre>
Line 2,077:
=={{header|Go}}==
{{trans|Icon and Unicon}}
<langsyntaxhighlight lang=go>package main
 
import (
Line 2,113:
fmt.Printf("%s -> %s (%d)\n", s, string(t), count)
}
}</langsyntaxhighlight>
{{out|Output of two runs}}
<pre>
Line 2,133:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang=groovy>def shuffle(text) {
def shuffled = (text as List)
for (sourceIndex in 0..<text.size()) {
Line 2,161:
def result = shuffle(text)
println "${result.original}, ${result.shuffled}, (${result.score})"
}</langsyntaxhighlight>
Output:
<pre>
Line 2,176:
We demonstrate several approaches here. In order to test the program we define a testing suite:
 
<langsyntaxhighlight lang=Haskell>shufflingQuality l1 l2 = length $ filter id $ zipWith (==) l1 l2
 
printTest prog = mapM_ test texts
Line 2,187:
texts = [ "abba", "abracadabra", "seesaw", "elk" , "grrrrrr"
, "up", "a", "aaaaa.....bbbbb"
, "Rosetta Code is a programming chrestomathy site." ]</langsyntaxhighlight>
 
=== Deterministic List-based solution ===
Line 2,193:
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).
 
<langsyntaxhighlight lang=Haskell>import Data.Vector ((//), (!))
import qualified Data.Vector as V
import Data.List (delete, find)
Line 2,212:
 
shuffle :: Eq a => [a] -> [a]
shuffle lst = swapShuffle lst lst</langsyntaxhighlight>
 
{{Out}}
Line 2,228:
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.
 
<langsyntaxhighlight lang=Haskell>perfectShuffle :: [a] -> [a]
perfectShuffle [] = []
perfectShuffle lst | odd n = b : shuffle (zip bs a)
Line 2,238:
shuffleP :: Eq a => [a] -> [a]
shuffleP lst = swapShuffle lst $ perfectShuffle lst</langsyntaxhighlight>
 
{{Out}}
Line 2,260:
Additional import:
 
<langsyntaxhighlight lang=Haskell>import Control.Monad.Random (getRandomR)</langsyntaxhighlight>
 
<langsyntaxhighlight lang=Haskell>randomShuffle :: [a] -> IO [a]
randomShuffle [] = return []
randomShuffle lst = do
Line 2,271:
shuffleR :: Eq a => [a] -> IO [a]
shuffleR lst = swapShuffle lst <$> randomShuffle lst</langsyntaxhighlight>
 
{{Out}}
Line 2,291:
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.
 
<langsyntaxhighlight lang=Haskell>{-# LANGUAGE TupleSections, LambdaCase #-}
import Conduit
import Control.Monad.Random (getRandomR)
Line 2,315:
 
shuffleW :: Eq a => Int -> [a] -> IO [a]
shuffleW k lst = yieldMany lst =$= shuffleC k $$ sinkList</langsyntaxhighlight>
 
Here we define a new conduit <code>shuffleC</code> which uses a moving window of length <tt>k</tt> and returns shuffled elements of upstream data.
Line 2,337:
Additional imports
 
<langsyntaxhighlight lang=Haskell>import Data.ByteString.Builder (charUtf8)
import Data.ByteString.Char8 (ByteString, unpack, pack)
import Data.Conduit.ByteString.Builder (builderToByteString)
import System.IO (stdin, stdout)</langsyntaxhighlight>
 
<langsyntaxhighlight lang=Haskell>
shuffleBS :: Int -> ByteString -> IO ByteString
shuffleBS n s =
Line 2,355:
sourceHandle stdin
=$ mapMC (shuffleBS 10)
$$ sinkHandle stdout</langsyntaxhighlight>
 
{{Out}}
Line 2,372:
 
Additionally, this can be trivially modified to randomize the shuffle by uncommenting the line
<langsyntaxhighlight lang=icon># every !t :=: ?t # Uncomment to get a random best shuffling</langsyntaxhighlight> in <tt>bestShuffle</tt>.
<langsyntaxhighlight lang=icon>procedure main(args)
while scram := bestShuffle(line := read()) do
write(line," -> ",scram," (",unchanged(line,scram),")")
Line 2,390:
every (count := 0) +:= (s1[i := 1 to *s1] == s2[i], 1)
return count
end</langsyntaxhighlight>
 
The code works in both Icon and Unicon.
Line 2,411:
Based on [http://rosettacode.org/mw/index.php?title=Best_shuffle&oldid=97419#J Dan Bron's approach]:
 
<langsyntaxhighlight lang=j>bestShuf =: verb define
yy=. <@({~ ?~@#)@I.@= y
y C.~ (;yy) </.~ (i.#y) |~ >./#@> yy
Line 2,420:
y,', ',b,' (',')',~":+/b=y
)
</syntaxhighlight>
</lang>
 
yy is (a list of) boxes of (lists of) indices where all characters selected by indices in a box are the same, and where the first box is the biggest box (contains the most indices). The phrase <code>({~ ?~@#)</code> shuffles the indices going into each box which makes the (deterministic) rotate which follows produce differing results sometimes (but only when that is possible).
Line 2,426:
Example:
 
<langsyntaxhighlight lang=j> fmtBest&>;:'abracadabra seesaw elk grrrrrr up a'
abracadabra, bdacararaab (0)
seesaw, eawess (0)
Line 2,432:
grrrrrr, rrrrrrg (5)
up, pu (0)
a, a (1)</langsyntaxhighlight>
 
=={{header|Java}}==
Translation of [[Best_shuffle#Icon_and_Unicon|Icon]] via [[Best_shuffle#AWK|AWK]]
<langsyntaxhighlight lang=java>import java.util.Random;
 
public class BestShuffle {
Line 2,481:
return count;
}
}</langsyntaxhighlight>
 
Output:
Line 2,495:
Based on the J implementation (and this would be a lot more concise if we used something like jQuery):
 
<langsyntaxhighlight lang=javascript>function raze(a) { // like .join('') except producing an array instead of a string
var r= [];
for (var j= 0; j<a.length; j++)
Line 2,541:
n+= ex.substr(j, 1) == r.substr(j,1) ?1 :0;
return ex+', '+r+', ('+n+')';
}</langsyntaxhighlight>
 
Example:
 
<langsyntaxhighlight lang=html><html><head><title></title></head><body><pre id="out"></pre></body></html>
<script type="text/javascript">
/* ABOVE CODE GOES HERE */
Line 2,551:
for (var i= 0; i<sample.length; i++)
document.getElementById('out').innerHTML+= disp(sample[i])+'\r\n';
</script></langsyntaxhighlight>
 
Produced:
Line 2,565:
The implementation in this section uses the deterministic "swap" algorithm found in other entries on this page.
 
<langsyntaxhighlight lang=jq>def count(s): reduce s as $i (0;.+1);
 
def swap($i;$j):
Line 2,598:
| . as $s
| bestShuffleArray
| "\($in), \(implode), (\( length - score($s) ))" ;</langsyntaxhighlight>
 
'''Examples:'''
<langsyntaxhighlight lang=jq>"abracadabra", "seesaw", "elk", "grrrrrr", "up", "a", "antidisestablishmentarianism"
| bestShuffle</langsyntaxhighlight>
 
'''Invocation and Output'''
Line 2,616:
=={{header|Julia}}==
{{trans|Python}}
<langsyntaxhighlight lang=julia># v0.6
 
function bestshuffle(str::String)::Tuple{String,Int}
Line 2,667:
shuffled, score = bestshuffle(word)
println("$word: $shuffled ($score)")
end</langsyntaxhighlight>
 
{{out}}
Line 2,679:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang=scala>import java.util.Random
 
object BestShuffle {
Line 2,715:
}
 
fun main(words: Array<String>) = words.forEach { println(BestShuffle(it)) }</langsyntaxhighlight>
 
{{out}}
Line 2,726:
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang=lb>'see Run BASIC solution
list$ = "abracadabra seesaw pop grrrrrr up a"
 
Line 2,751:
next i
bestShuffle$ = s2$
end function</langsyntaxhighlight>
output
<pre>
Line 2,763:
 
=={{header|Lua}}==
<langsyntaxhighlight lang=lua>math.randomseed(os.time())
 
local function shuffle(t)
Line 2,803:
 
test(true)
test(false)</langsyntaxhighlight>
{{out}}
<pre>RANDOM:
Line 2,822:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight lang=Mathematica>BestShuffle[data_] :=
Flatten[{data,First[SortBy[
List[#, StringLength[data]-HammingDistance[#,data]] & /@ StringJoin /@ Permutations[StringSplit[data, ""]], Last]]}]
 
Print[#[[1]], "," #[[2]], ",(", #[[3]], ")"] & /@ BestShuffle /@ {"abracadabra","seesaw","elk","grrrrrr","up","a"}
</syntaxhighlight>
</lang>
 
Output :
Line 2,839:
=={{header|Nim}}==
{{trans|Java}}
<langsyntaxhighlight lang=Nim>import times
import sequtils
import strutils
Line 2,873:
let shuffled = bestShuffle(w)
echo "$1 $2 $3" % [w, shuffled, $count(w, shuffled)]
</syntaxhighlight>
</lang>
 
Run:
Line 2,889:
Deterministic
 
<langsyntaxhighlight lang=ocaml>let best_shuffle s =
let len = String.length s in
let r = String.copy s in
Line 2,925:
test "up";
test "a";
;;</langsyntaxhighlight>
 
Run:
Line 2,940:
=={{header|Pascal}}==
{{works with|Free_Pascal}}
<langsyntaxhighlight lang=pascal>program BestShuffleDemo(output);
function BestShuffle(s: string): string;
Line 2,979:
writeln(original[i], ', ', shuffle, ', (', score, ')');
end;
end.</langsyntaxhighlight>
Output:
<pre>% ./BestShuffle
Line 2,992:
The Algorithm::Permute module does not ship with perl, but is freely available from CPAN.
 
<langsyntaxhighlight lang=perl>use strict;
use warnings;
use List::Util qw(shuffle);
Line 3,021:
}
 
</syntaxhighlight>
</lang>
{{out|Output of two runs}}
<pre>abracadabra, dabrabacaar, 0
Line 3,048:
 
{{trans|go}}
<langsyntaxhighlight lang=perl>use strict;
use warnings;
use List::Util qw(shuffle);
Line 3,075:
print "$original_word, $word, $score\n";
}
</syntaxhighlight>
</lang>
 
The output has the same format as the first perl implementation,
Line 3,081:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight lang=Phix>(phixonline)-->
<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>
Line 3,099:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s -&gt; %s (%d)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_eq</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">))})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,121:
=={{header|PHP}}==
Translation of [[Best_shuffle#Icon_and_Unicon|Icon]] via [[Best_shuffle#AWK|AWK]]
<langsyntaxhighlight lang=php>foreach (split(' ', 'abracadabra seesaw pop grrrrrr up a') as $w)
echo bestShuffle($w) . '<br>';
 
Line 3,145:
$cnt++;
return "($cnt)";
}</langsyntaxhighlight>
 
Output:
Line 3,158:
Using a CP (Constraint Programming) solver guarantees an optimal solution. This is deterministic since the solve heuristic ("split") always give the same first result.
 
<langsyntaxhighlight lang=Picat>import cp.
 
go =>
Line 3,221:
foreach(E in L)
Occ.put(E, Occ.get(E,0) + 1)
end.</langsyntaxhighlight>
 
{{out}}
Line 3,235:
===All optimal solutions===
Using a constraint solver makes it quite easy to generate all optimal solutions.
<langsyntaxhighlight lang=Picat>go2 ?=>
Words = ["abracadabra",
"seesaw",
Line 3,262:
fail,
nl.
go2 => true.</langsyntaxhighlight>
 
{{out}}
Line 3,309:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight lang=PicoLisp>(de bestShuffle (Str)
(let Lst NIL
(for C (setq Str (chop Str))
Line 3,322:
(setq Lst (delete @ Lst)) ) )
Str )
(prinl Str " " Res " (" (cnt = Str Res) ")") ) ) )</langsyntaxhighlight>
Output:
<pre>: (bestShuffle "abracadabra")
Line 3,343:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang=pli>shuffle: procedure options (main); /* 14/1/2011 */
declare (s, saves) character (20) varying, c character (1);
declare t(length(s)) bit (1);
Line 3,395:
end search;
 
end shuffle;</langsyntaxhighlight>
 
OUTPUT:
Line 3,414:
=={{header|PowerShell}}==
{{works with|PowerShell|3}}
<langsyntaxhighlight 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)
function Get-BestScore ( [string]$String )
Line 3,465:
$Shuffle = ( [string[]]$S2 -join '' )
return $Shuffle
}</langsyntaxhighlight>
<langsyntaxhighlight lang=PowerShell>ForEach ( $String in ( 'abracadabra', 'seesaw', 'elk', 'grrrrrr', 'up', 'a' ) )
{
$Shuffle = Get-BestShuffle $String
$Score = Get-BestScore $String
"$String, $Shuffle, ($Score)"
}</langsyntaxhighlight>
{{out}}
<pre>abracadabra, craradabaab, (0)
Line 3,482:
=={{header|Prolog}}==
Works with SWI-Prolog
<langsyntaxhighlight lang=Prolog>:- dynamic score/2.
 
best_shuffle :-
Line 3,556:
run(Var,[Other|RRest], [1,Var],[Other|RRest]):-
dif(Var,Other).
</syntaxhighlight>
</lang>
 
output : <pre> ?- test.
Line 3,570:
===Version with random result===
====solution====
<langsyntaxhighlight lang=Prolog>
:- system:set_prolog_flag(double_quotes,codes) .
 
Line 3,656:
.
 
</syntaxhighlight>
</lang>
 
====output====
Line 3,694:
=={{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.
<langsyntaxhighlight lang=PureBasic>Structure charInfo
Char.s
List Position.i()
Line 3,803:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>abracadabra, daabarbraac, (0)
Line 3,815:
===Swap if it is locally better algorithm===
With added randomization of swaps!
<langsyntaxhighlight lang=python>import random
 
def count(w1,wnew):
Line 3,842:
for w in test_words:
wnew, c = best_shuffle(w)
print("%29s, %-29s ,(%i)" % (w, wnew, c))</langsyntaxhighlight>
 
;Sample output
Line 3,878:
===Alternative algorithm #1===
 
<langsyntaxhighlight lang=python>#!/usr/bin/env python
 
def best_shuffle(s):
Line 3,927:
for s in "abracadabra", "seesaw", "elk", "grrrrrr", "up", "a":
shuffled, score = best_shuffle(s)
print("%s, %s, (%d)" % (s, shuffled, score))</langsyntaxhighlight>
 
Output: <pre>abracadabra, raabarabacd, (0)
Line 3,937:
 
=={{header|Racket}}==
<langsyntaxhighlight lang=Racket>
#lang racket
 
Line 3,958:
(define sh (best-shuffle s))
(printf " ~a, ~a, (~a)\n" s sh (count-same s sh)))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,974:
{{works with|Rakudo Star|2015.12}}
 
<syntaxhighlight lang=raku perl6line>sub best-shuffle(Str $orig) {
 
my @s = $orig.comb;
Line 3,997:
 
printf "%s, %s, (%d)\n", $_, best-shuffle $_
for <abracadabra seesaw elk grrrrrr up a>;</langsyntaxhighlight>
{{out}}
<pre>
Line 4,010:
=={{header|Rascal}}==
{{incomplete|Rascal|No output given.}}
<langsyntaxhighlight lang=Rascal>import Prelude;
 
public tuple[str, str, int] bestShuffle(str s){
Line 4,022:
public int countSame(list[int] permutations, list[int] characters){
return (0 | it + 1 | n <- index(characters), permutations[n] == characters[n]);
}</langsyntaxhighlight>
 
=={{header|REXX}}==
<langsyntaxhighlight 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.*/
if $='' then $= 'tree abracadabra seesaw elk grrrrrr up a' /*use the defaults?*/
Line 4,054:
else x= left(x, k-1)substr(x, k+1, 1)a || substr(x,k+2)
end /*k*/
return x</langsyntaxhighlight>
{{out|output|text=&nbsp; (with a freebie thrown in):}}
<pre>
Line 4,067:
 
=={{header|Ring}}==
<langsyntaxhighlight lang=ring>
# Project : Best shuffle
 
Line 4,101:
bestshuffle = s2
return bestshuffle
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,116:
{{trans|Raku}}
 
<langsyntaxhighlight lang=ruby>def best_shuffle(s)
# Fill _pos_ with positions in the order
# that we want to fill them.
Line 4,151:
%w(abracadabra seesaw elk grrrrrr up a).each do |word|
puts "%s, %s, (%d)" % [word, *best_shuffle(word)]
end</langsyntaxhighlight>
 
{{out}}
Line 4,164:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang=runbasic>list$ = "abracadabra seesaw pop grrrrrr up a"
 
while word$(list$,ii + 1," ") <> ""
Line 4,188:
next i
bestShuffle$ = s2$
end function</langsyntaxhighlight>
 
Output:
Line 4,201:
=={{header|Rust}}==
{{libheader|rand}}
<langsyntaxhighlight lang=rust>extern crate permutohedron;
extern crate rand;
 
Line 4,336:
w0.iter().zip(w1.iter()).filter(|z| z.0 == z.1).count()
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,349:
=={{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.
<langsyntaxhighlight lang=scala>
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)
Line 4,384:
 
}
</syntaxhighlight>
</lang>
The test code:
<langsyntaxhighlight lang=scala>
def main(args: Array[String]): Unit = {
println(bestShuffle("abracadabra"));
Line 4,397:
BestShuffleSpecification.check
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,408:
</pre>
The ScalaCheck code
<langsyntaxhighlight lang=scala>
object BestShuffleSpecification extends Properties("BestShuffle") {
 
Line 4,427:
 
}
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang=scheme>
(define count
(lambda (str1 str2)
Line 4,496:
(number->string (count str shuffled)) ")\n"))))
'("abracadabra" "seesaw" "elk" "grrrrrr" "up" "a"))
</syntaxhighlight>
</lang>
 
Output:
Line 4,509:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang=seed7>$ include "seed7_05.s7i";
 
const func string: bestShuffle (in string: stri) is func
Line 4,549:
writeln(original <& ", " <& shuffled <& ", (" <& score <& ")");
end for;
end func;</langsyntaxhighlight>
 
Output:
Line 4,563:
=={{header|Sidef}}==
{{trans|Go}}
<langsyntaxhighlight lang=ruby>func best_shuffle(String orig) -> (String, Number) {
 
var s = orig.chars
Line 4,583:
var (sword, score) = best_shuffle(word)
"%-12s %12s: %d\n".printf(word, sword, score)
}</langsyntaxhighlight>
{{out}}
<pre>abracadabra daabacarrab: 0
Line 4,594:
=={{header|Tcl}}==
{{tcllib|struct::list}}
<langsyntaxhighlight lang=tcl>package require Tcl 8.5
package require struct::list
 
Line 4,614:
set best [join $best ""]
return "$str,$best,($score)"
}</langsyntaxhighlight>
Demonstration:
<langsyntaxhighlight lang=tcl>foreach sample {abracadabra seesaw elk grrrrrr up a} {
puts [bestshuffle $sample]
}</langsyntaxhighlight>
Output:
<pre>
Line 4,631:
=={{header|Ursala}}==
An implementation based on the J solution looks like this.
<langsyntaxhighlight lang=Ursala>#import std
#import nat
 
Line 4,640:
#show+
 
main = ~&LS <.~&l,@r :/` ,' ('--+ --')'+ ~&h+ %nP+ length@plrEF>^(~&,shuffle)* words</langsyntaxhighlight>
A solution based on exponential search would use this definition of <code>shuffle</code> (cf. Haskell and Tcl).
<langsyntaxhighlight lang=Ursala>shuffle = ~&r+ length@plrEZF$^^D/~& permutations</langsyntaxhighlight>
output:
<pre>abracadabra caarrbabaad (0)
Line 4,653:
=={{header|VBA}}==
 
<syntaxhighlight lang=vb>
<lang vb>
Option Explicit
 
Line 4,748:
NbLettersDiff = C.Count
End Function
</syntaxhighlight>
</lang>
{{out}}
<pre>a ==> a (Score : 1)
Line 4,761:
=={{header|VBScript}}==
{{trans|Java}}
<langsyntaxhighlight lang=vb>'Best Shuffle Task
'VBScript Implementation
 
Line 4,812:
For Each word In word_list
WScript.StdOut.WriteLine word & "," & bestshuffle(word)
Next</langsyntaxhighlight>
 
{{Out}}
Line 4,824:
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang=ecmascript>import "random" for Random
 
class BestShuffle {
Line 4,865:
 
var words = ["tree", "abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"]
words.each { |w| System.print(BestShuffle.invoke(w)) }</langsyntaxhighlight>
 
{{out}}
Line 4,879:
 
=={{header|XPL0}}==
<langsyntaxhighlight lang=XPL0>include c:\cxpl\codes; \'code' declarations
string 0; \use zero-terminated string convention
 
Line 4,913:
[S:= ["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"];
for I:= 0 to 5 do Shuffle(S(I));
]</langsyntaxhighlight>
 
Output:
Line 4,928:
{{trans|D}}
{{trans|Common Lisp}}
<langsyntaxhighlight lang=zkl>fcn bestShuffle(str){
s:=str.split("").shuffle(); // -->List
if(not s) return(str,str.len()); // can't shuffle "" or "a"
Line 4,942:
}
return(s.concat(), s.zipWith('==,str).sum(0));
}</langsyntaxhighlight>
<langsyntaxhighlight lang=zkl>ss:=T("abracadabra","immediately","grrrrrr","seesaw","pop","up","a","");
foreach s in (ss){
ns,cnt:=bestShuffle(s);
println("%s --> %s (%d)".fmt(s,ns,cnt));
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,962:
=={{header|ZX Spectrum Basic}}==
{{trans|AWK}}
<langsyntaxhighlight lang=zxbasic>10 FOR n=1 TO 6
20 READ w$
30 GO SUB 1000
Line 4,981:
1130 RETURN
2000 DATA "abracadabra","seesaw","elk","grrrrrr","up","a"
</syntaxhighlight>
</lang>
{{out}}
<pre>abracadabra caadrbabaar 0
10,333

edits