Best shuffle: Difference between revisions

Content added Content deleted
m (→‎{{header|D}}: add cyclic group version)
m (→‎{{header|D}}: add minimum randomness)
Line 156: Line 156:
Using idea from [http://rosettacode.org/wiki/Talk:Best_shuffle#J_implementation_notes J implementation notes] at discussion page.
Using idea from [http://rosettacode.org/wiki/Talk:Best_shuffle#J_implementation_notes J implementation notes] at discussion page.
{{works with|D|2.051}}
{{works with|D|2.051}}
<lang d>import std.stdio, std.string, std.conv, std.algorithm, std.range ;
<lang d>import std.stdio, std.string, std.conv, std.algorithm, std.range, std.random ;


string shuffle(const string txt) {
string shuffle(const string txt, bool bRandom = true) {
if(txt.length <= 3) return text(txt[1..$] ~ txt[0]) ;
if(txt.length <= 3) return text(txt[1..$] ~ txt[0]) ;
auto s = dtext(txt) ;
auto s = dtext(txt) ;
Line 172: Line 172:


auto raw = reduce!"a ~ b"(gpCyc) ; // get original idx order
auto raw = reduce!"a ~ b"(gpCyc) ; // get original idx order
foreach(ref g;gpCyc) // cycling within group
foreach(ref g;gpCyc) { // cycling within group
g = (g[1..$] ~ g[0]) ;
auto cut = (bRandom && g.length > 2) ? uniform(1, g.length - 1) : 1 ;
g = (g[cut..$] ~ g[0..cut]) ;
}
auto cyc = reduce!"a ~ b"(gpCyc) ; // get cyclic idx order
auto cyc = reduce!"a ~ b"(gpCyc) ; // get cyclic idx order


Line 183: Line 185:


void main() {
void main() {
auto txt = ["abracadabra", "eesaw", "elk", "grrrrrr", "up", "a"] ;
auto txt = ["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"] ;
auto fmx = format("%%%ds", reduce!max(map!"a.length"(txt))) ;
auto fmx = format("%%%ds", reduce!max(map!"a.length"(txt))) ;
foreach(t;txt)
foreach(t;txt)
writefln(fmx ~" -> "~fmx~" (%d)",
writefln(fmx ~" -> "~fmx~" (%d)",
t, shuffle(t), count!"a[0]==a[1]"(zip(t,shuffle(t)))) ;
t, shuffle(t), count!"a[0]==a[1]"(zip(t,shuffle(t)))) ;
auto r ="11-22-333-44-55" ;
writeln(r) ;
foreach(loop;0..4)
writefln("%s (%d)",
shuffle(r), count!"a[0]==a[1]"(zip(r,shuffle(r)))) ;
}</lang>
}</lang>
part of output:
<pre>11-22-333-44-55
-354431223--51- (0)
--34-35242-3511 (0)
--34435223--511 (0)
-354431223--51- (0)</pre>


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