Best shuffle: Difference between revisions
m
syntax highlighting fixup automation
mNo edit summary |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 37:
{{trans|Python}}
<
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))</
{{out}}
Line 79:
=={{header|Action!}}==
<
BYTE i,j,len
CHAR tmp
Line 118:
Test("up")
Test("a")
RETURN</
{{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}}
<
with Ada.Strings.Unbounded;
Line 181:
end;
end loop;
end Best_Shuffle;</
Output:
Line 193:
=={{header|ALGOL 68}}==
{{Trans|Action!}}
<
PROC best shuffle = ( STRING orig )STRING:
BEGIN
Line 224:
test( "up" );
test( "a" )
END</
{{out}}
<pre>
Line 237:
=={{header|Arturo}}==
<
count: function [s1 s2][
res: 0
Line 275:
sf: bestShuffle w
print [w "->" sf "| count:" count w sf]
]</
{{out}}
Line 288:
=={{header|AutoHotkey}}==
<
Loop Parse, Words,`,
out .= Score(A_LoopField, Shuffle(A_LoopField))
Line 339:
r++
return a ", " b ", (" r ")`n"
}</
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.
<
scram = best_shuffle($0)
print $0 " -> " scram " (" unchanged($0, scram) ")"
Line 392:
}
return count
}</
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.
<
# 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"]
}
}</
Output:
<
abracadabra, baarrcadaab, (0)
seesaw, essewa, (0)
Line 495:
grrrrrr, rgrrrrr, (5)
up, pu, (0)
a, a, (1)</
The output might change if the <tt>for (c in set)</tt> loop iterates the array in a different order.
=={{header|BaCon}}==
<
FOR z = 0 TO UBOUND(case$)-1
Line 517:
PRINT MERGE$(result$), ":", total
NEXT</
{{output}}
<pre>
Line 531:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
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%) + ")"</
Output (varies between runs):
<pre>
Line 573:
=={{header|Bracmat}}==
Not optimized:
<
( shuffle
= m car cdr todo a z count string
Line 602:
)
& Done
</syntaxhighlight>
Optimized (~100 x faster):
<
( shuffle
= m car cdr todo a z count M string tried
Line 640:
)
& Done
</syntaxhighlight>
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.
<
#include <stdio.h>
#include <string.h>
Line 768:
return EXIT_SUCCESS;
}</
Output:
<pre>abracadabra, brabacadaar, (0)
Line 781:
===Version with random result===
<
#include <stdlib.h>
#include <string.h>
Line 886:
do_string("");
return 0;
}</
grrrrrr -> rrgrrrr, overlap 5
elk -> kel, overlap 0
seesaw -> ewsesa, overlap 0
-> , overlap 0</
===Deterministic method===
<
#include <string.h>
Line 928:
}
return 0;
}</
=={{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.:
<
Which will immediately shuffle each word.
A sequential solution, which always produces the same output for the same input.
<
using System;
using System.Text;
Line 1,062:
}
}
</syntaxhighlight>
And a randomized solution, which will produce a more or less different result on every run:
<
using System;
using System.Text;
Line 1,191:
}
}
</syntaxhighlight>
A sample output for the sequential shuffle:
Line 1,217:
{{works with|C++|11}}
{{trans|Java}}
<
#include <sstream>
#include <algorithm>
Line 1,261:
cout << bs(basic_string<char>(arguments[i])) << endl;
return 0;
}</
{{out}}
<pre>abracadabra
Line 1,279:
Uses same method as J
<
(->> (map = before after)
(filter true? ,)
Line 1,332:
["grrrrrr" "rgrrrrr" 5]
["up" "pu" 0]
["a" "a" 1]]</
=={{header|Common Lisp}}==
<
(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"))</
Output:
abracadabra caadrbabaar (0)
Line 1,367:
===Version 2===
<
(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>
The output is:
<
seesaw: (ewsase 0)
elk: (kel 0)
Line 1,422:
up: (pu 0)
a: (a 1)
</syntaxhighlight>
=={{header|Crystal}}==
{{trans|Ruby}}
<
# 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</
{{out}}
Line 1,482:
===Version with random result===
Translation of [[Best_shuffle#Icon_and_Unicon|Icon]] via [[Best_shuffle#AWK|AWK]]
<
std.traits, std.typecons;
Line 1,522:
writefln("%s : %s (%d)", entry, res[]);
}
}</
===Deterministic approach===
<
extern(C) pure nothrow void* alloca(in size_t size);
Line 1,627:
writefln("%s, %s, (%d)", txt, result, nEqual);
}
}</
{{out}}
<pre>abracadabra, brabacadaar, (0)
Line 1,642:
{{libheader| System.Generics.Collections}}
{{Trans|C#}}
<
program Best_shuffle;
Line 1,781:
Readln;
end.
</syntaxhighlight>
=={{header|Elena}}==
ELENA 5.0 :
<
import extensions;
import extensions'text;
Line 1,831:
console.readChar()
}</
{{out}}
<pre>
Line 1,844:
=={{header|Erlang}}==
Deterministic version.
<
-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>
{{out}}
<pre>
Line 1,898:
=={{header|FreeBASIC}}==
{{trans|Liberty BASIC}}
<
Dim As String*11 lista(6) => {"abracadabra","seesaw","pop","grrrrrr","up","a"}
Line 1,927:
Next b
Sleep
</syntaxhighlight>
{{out}}
<pre>
Line 1,939:
=={{header|Free Pascal}}==
<
Program BestShuffle;
Line 1,986:
End.
</syntaxhighlight>
{{out}}
<pre>
Line 1,998:
=={{header|FutureBasic}}==
<
include "Tlbx GameplayKit.incl"
Line 2,043:
HandleEvents
</syntaxhighlight>
Output with four shuffles:
<pre>
Line 2,077:
=={{header|Go}}==
{{trans|Icon and Unicon}}
<
import (
Line 2,113:
fmt.Printf("%s -> %s (%d)\n", s, string(t), count)
}
}</
{{out|Output of two runs}}
<pre>
Line 2,133:
=={{header|Groovy}}==
<
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})"
}</
Output:
<pre>
Line 2,176:
We demonstrate several approaches here. In order to test the program we define a testing suite:
<
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." ]</
=== 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).
<
import qualified Data.Vector as V
import Data.List (delete, find)
Line 2,212:
shuffle :: Eq a => [a] -> [a]
shuffle lst = swapShuffle lst lst</
{{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.
<
perfectShuffle [] = []
perfectShuffle lst | odd n = b : shuffle (zip bs a)
Line 2,238:
shuffleP :: Eq a => [a] -> [a]
shuffleP lst = swapShuffle lst $ perfectShuffle lst</
{{Out}}
Line 2,260:
Additional import:
<
<
randomShuffle [] = return []
randomShuffle lst = do
Line 2,271:
shuffleR :: Eq a => [a] -> IO [a]
shuffleR lst = swapShuffle lst <$> randomShuffle lst</
{{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.
<
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</
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
<
import Data.ByteString.Char8 (ByteString, unpack, pack)
import Data.Conduit.ByteString.Builder (builderToByteString)
import System.IO (stdin, stdout)</
<
shuffleBS :: Int -> ByteString -> IO ByteString
shuffleBS n s =
Line 2,355:
sourceHandle stdin
=$ mapMC (shuffleBS 10)
$$ sinkHandle stdout</
{{Out}}
Line 2,372:
Additionally, this can be trivially modified to randomize the shuffle by uncommenting the line
<
<
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</
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]:
<
yy=. <@({~ ?~@#)@I.@= y
y C.~ (;yy) </.~ (i.#y) |~ >./#@> yy
Line 2,420:
y,', ',b,' (',')',~":+/b=y
)
</syntaxhighlight>
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:
<
abracadabra, bdacararaab (0)
seesaw, eawess (0)
Line 2,432:
grrrrrr, rrrrrrg (5)
up, pu (0)
a, a (1)</
=={{header|Java}}==
Translation of [[Best_shuffle#Icon_and_Unicon|Icon]] via [[Best_shuffle#AWK|AWK]]
<
public class BestShuffle {
Line 2,481:
return count;
}
}</
Output:
Line 2,495:
Based on the J implementation (and this would be a lot more concise if we used something like jQuery):
<
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+')';
}</
Example:
<
<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></
Produced:
Line 2,565:
The implementation in this section uses the deterministic "swap" algorithm found in other entries on this page.
<
def swap($i;$j):
Line 2,598:
| . as $s
| bestShuffleArray
| "\($in), \(implode), (\( length - score($s) ))" ;</
'''Examples:'''
<
| bestShuffle</
'''Invocation and Output'''
Line 2,616:
=={{header|Julia}}==
{{trans|Python}}
<
function bestshuffle(str::String)::Tuple{String,Int}
Line 2,667:
shuffled, score = bestshuffle(word)
println("$word: $shuffled ($score)")
end</
{{out}}
Line 2,679:
=={{header|Kotlin}}==
{{trans|Java}}
<
object BestShuffle {
Line 2,715:
}
fun main(words: Array<String>) = words.forEach { println(BestShuffle(it)) }</
{{out}}
Line 2,726:
=={{header|Liberty BASIC}}==
<
list$ = "abracadabra seesaw pop grrrrrr up a"
Line 2,751:
next i
bestShuffle$ = s2$
end function</
output
<pre>
Line 2,763:
=={{header|Lua}}==
<
local function shuffle(t)
Line 2,803:
test(true)
test(false)</
{{out}}
<pre>RANDOM:
Line 2,822:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
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>
Output :
Line 2,839:
=={{header|Nim}}==
{{trans|Java}}
<
import sequtils
import strutils
Line 2,873:
let shuffled = bestShuffle(w)
echo "$1 $2 $3" % [w, shuffled, $count(w, shuffled)]
</syntaxhighlight>
Run:
Line 2,889:
Deterministic
<
let len = String.length s in
let r = String.copy s in
Line 2,925:
test "up";
test "a";
;;</
Run:
Line 2,940:
=={{header|Pascal}}==
{{works with|Free_Pascal}}
<
function BestShuffle(s: string): string;
Line 2,979:
writeln(original[i], ', ', shuffle, ', (', score, ')');
end;
end.</
Output:
<pre>% ./BestShuffle
Line 2,992:
The Algorithm::Permute module does not ship with perl, but is freely available from CPAN.
<
use warnings;
use List::Util qw(shuffle);
Line 3,021:
}
</syntaxhighlight>
{{out|Output of two runs}}
<pre>abracadabra, dabrabacaar, 0
Line 3,048:
{{trans|go}}
<
use warnings;
use List::Util qw(shuffle);
Line 3,075:
print "$original_word, $word, $score\n";
}
</syntaxhighlight>
The output has the same format as the first perl implementation,
Line 3,081:
=={{header|Phix}}==
<!--<
<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 -> %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>
<!--</
{{out}}
<pre>
Line 3,121:
=={{header|PHP}}==
Translation of [[Best_shuffle#Icon_and_Unicon|Icon]] via [[Best_shuffle#AWK|AWK]]
<
echo bestShuffle($w) . '<br>';
Line 3,145:
$cnt++;
return "($cnt)";
}</
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.
<
go =>
Line 3,221:
foreach(E in L)
Occ.put(E, Occ.get(E,0) + 1)
end.</
{{out}}
Line 3,235:
===All optimal solutions===
Using a constraint solver makes it quite easy to generate all optimal solutions.
<
Words = ["abracadabra",
"seesaw",
Line 3,262:
fail,
nl.
go2 => true.</
{{out}}
Line 3,309:
=={{header|PicoLisp}}==
<
(let Lst NIL
(for C (setq Str (chop Str))
Line 3,322:
(setq Lst (delete @ Lst)) ) )
Str )
(prinl Str " " Res " (" (cnt = Str Res) ")") ) ) )</
Output:
<pre>: (bestShuffle "abracadabra")
Line 3,343:
=={{header|PL/I}}==
<
declare (s, saves) character (20) varying, c character (1);
declare t(length(s)) bit (1);
Line 3,395:
end search;
end shuffle;</
OUTPUT:
Line 3,414:
=={{header|PowerShell}}==
{{works with|PowerShell|3}}
<
# (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
}</
<
{
$Shuffle = Get-BestShuffle $String
$Score = Get-BestScore $String
"$String, $Shuffle, ($Score)"
}</
{{out}}
<pre>abracadabra, craradabaab, (0)
Line 3,482:
=={{header|Prolog}}==
Works with SWI-Prolog
<
best_shuffle :-
Line 3,556:
run(Var,[Other|RRest], [1,Var],[Other|RRest]):-
dif(Var,Other).
</syntaxhighlight>
output : <pre> ?- test.
Line 3,570:
===Version with random result===
====solution====
<
:- system:set_prolog_flag(double_quotes,codes) .
Line 3,656:
.
</syntaxhighlight>
====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.
<
Char.s
List Position.i()
Line 3,803:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
Sample output:
<pre>abracadabra, daabarbraac, (0)
Line 3,815:
===Swap if it is locally better algorithm===
With added randomization of swaps!
<
def count(w1,wnew):
Line 3,842:
for w in test_words:
wnew, c = best_shuffle(w)
print("%29s, %-29s ,(%i)" % (w, wnew, c))</
;Sample output
Line 3,878:
===Alternative algorithm #1===
<
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))</
Output: <pre>abracadabra, raabarabacd, (0)
Line 3,937:
=={{header|Racket}}==
<
#lang racket
Line 3,958:
(define sh (best-shuffle s))
(printf " ~a, ~a, (~a)\n" s sh (count-same s sh)))
</syntaxhighlight>
{{out}}
<pre>
Line 3,974:
{{works with|Rakudo Star|2015.12}}
<syntaxhighlight lang=raku
my @s = $orig.comb;
Line 3,997:
printf "%s, %s, (%d)\n", $_, best-shuffle $_
for <abracadabra seesaw elk grrrrrr up a>;</
{{out}}
<pre>
Line 4,010:
=={{header|Rascal}}==
{{incomplete|Rascal|No output given.}}
<
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]);
}</
=={{header|REXX}}==
<
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</
{{out|output|text= (with a freebie thrown in):}}
<pre>
Line 4,067:
=={{header|Ring}}==
<
# Project : Best shuffle
Line 4,101:
bestshuffle = s2
return bestshuffle
</syntaxhighlight>
Output:
<pre>
Line 4,116:
{{trans|Raku}}
<
# 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</
{{out}}
Line 4,164:
=={{header|Run BASIC}}==
<
while word$(list$,ii + 1," ") <> ""
Line 4,188:
next i
bestShuffle$ = s2$
end function</
Output:
Line 4,201:
=={{header|Rust}}==
{{libheader|rand}}
<
extern crate rand;
Line 4,336:
w0.iter().zip(w1.iter()).filter(|z| z.0 == z.1).count()
}
</syntaxhighlight>
{{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.
<
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>
The test code:
<
def main(args: Array[String]): Unit = {
println(bestShuffle("abracadabra"));
Line 4,397:
BestShuffleSpecification.check
}
</syntaxhighlight>
{{out}}
<pre>
Line 4,408:
</pre>
The ScalaCheck code
<
object BestShuffleSpecification extends Properties("BestShuffle") {
Line 4,427:
}
</syntaxhighlight>
=={{header|Scheme}}==
<
(define count
(lambda (str1 str2)
Line 4,496:
(number->string (count str shuffled)) ")\n"))))
'("abracadabra" "seesaw" "elk" "grrrrrr" "up" "a"))
</syntaxhighlight>
Output:
Line 4,509:
=={{header|Seed7}}==
<
const func string: bestShuffle (in string: stri) is func
Line 4,549:
writeln(original <& ", " <& shuffled <& ", (" <& score <& ")");
end for;
end func;</
Output:
Line 4,563:
=={{header|Sidef}}==
{{trans|Go}}
<
var s = orig.chars
Line 4,583:
var (sword, score) = best_shuffle(word)
"%-12s %12s: %d\n".printf(word, sword, score)
}</
{{out}}
<pre>abracadabra daabacarrab: 0
Line 4,594:
=={{header|Tcl}}==
{{tcllib|struct::list}}
<
package require struct::list
Line 4,614:
set best [join $best ""]
return "$str,$best,($score)"
}</
Demonstration:
<
puts [bestshuffle $sample]
}</
Output:
<pre>
Line 4,631:
=={{header|Ursala}}==
An implementation based on the J solution looks like this.
<
#import nat
Line 4,640:
#show+
main = ~&LS <.~&l,@r :/` ,' ('--+ --')'+ ~&h+ %nP+ length@plrEF>^(~&,shuffle)* words</
A solution based on exponential search would use this definition of <code>shuffle</code> (cf. Haskell and Tcl).
<
output:
<pre>abracadabra caarrbabaad (0)
Line 4,653:
=={{header|VBA}}==
<syntaxhighlight lang=vb>
Option Explicit
Line 4,748:
NbLettersDiff = C.Count
End Function
</syntaxhighlight>
{{out}}
<pre>a ==> a (Score : 1)
Line 4,761:
=={{header|VBScript}}==
{{trans|Java}}
<
'VBScript Implementation
Line 4,812:
For Each word In word_list
WScript.StdOut.WriteLine word & "," & bestshuffle(word)
Next</
{{Out}}
Line 4,824:
=={{header|Wren}}==
{{trans|Kotlin}}
<
class BestShuffle {
Line 4,865:
var words = ["tree", "abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"]
words.each { |w| System.print(BestShuffle.invoke(w)) }</
{{out}}
Line 4,879:
=={{header|XPL0}}==
<
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));
]</
Output:
Line 4,928:
{{trans|D}}
{{trans|Common Lisp}}
<
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));
}</
<
foreach s in (ss){
ns,cnt:=bestShuffle(s);
println("%s --> %s (%d)".fmt(s,ns,cnt));
}</
{{out}}
<pre>
Line 4,962:
=={{header|ZX Spectrum Basic}}==
{{trans|AWK}}
<
20 READ w$
30 GO SUB 1000
Line 4,981:
1130 RETURN
2000 DATA "abracadabra","seesaw","elk","grrrrrr","up","a"
</syntaxhighlight>
{{out}}
<pre>abracadabra caadrbabaar 0
|