Jump to content

Best shuffle: Difference between revisions

401 bytes removed ,  13 years ago
Line 628:
 
=={{header|D}}==
{{works with|D|2}}{{trans|AWK}}
<lang d>import std.stdio, std.random, std.algorithm, std.array, std.conv, std.range, std.typecons;
 
auto bestShuffle(in dchar[] s1) {
 
bool hasSamePositions(in dchar[] r1, in dchar[] r2, uint ignore) {
foreach (r; zip(r1, r2)) {
if (r[0] == r[1] && ignore-- == 0) return true;
}
return false;
}
 
const len = s1.length;
auto s2 = s1.dup;
uint numToIgnorerandomShuffle(s2);
constforeach(i; len0 =.. s1s2.length;)
 
if (len > foreach(j; 0 .. s2.length) {
auto numProbChars = sort! if ("ai != j && s2[1i] >!= bs1[1j]")(array(group( && s2.sort)))[0j] != s1[1i];) {
if (numProbChars > len / 2) { swap(s2[i], s2[j]);
numToIgnore = numProbChars - (len - numProbChars)break;
}
do {
for (size_t i = len; i > 1; i--) {
swap(s2[i - 1], s2[uniform(0, i)]);
}
} while (hasSamePositions(s1, s2, numToIgnore));
}
 
return tuple(s2, numToIgnore);count!(q{a[0] == a[1]})(zip(s1,s2)));
}</lang>
}
 
<lang d>void main(string[] args) {
if (args.length > 1) {
string entry = join(args[1..$], " ");
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.