Best shuffle: Difference between revisions

Content added Content deleted
(→‎{{header|D}}: more concise)
Line 631: Line 631:
<lang d>import std.stdio, std.random, std.algorithm, std.conv, std.range, std.typecons;
<lang d>import std.stdio, std.random, std.algorithm, std.conv, std.range, std.typecons;


auto bestShuffle(in dstring s1){
auto bestShuffle(in dstring o){
auto s2 = s1.dup;
auto s = o.dup;
randomShuffle(s2);
randomShuffle(s);
foreach(i; 0 .. s2.length)
foreach(i, ref ci; s)
foreach(j; 0 .. s2.length)
foreach(j, ref cj; s)
if (i != j && s2[i] != s1[j] && s2[j] != s1[i]) {
if (i != j && ci != o[j] && cj != o[i]) {
swap(s2[i], s2[j]);
swap(ci, cj);
break;
break;
}
}


return tuple(s2, count!q{a[0] == a[1]}(zip(s1,s2)));
return tuple(s, count!q{a[0] == a[1]}(zip(s, o)));
}</lang>
}</lang>