Best shuffle: Difference between revisions

261 bytes removed ,  13 years ago
→‎{{header|D}}: more tinkering
(→‎{{header|D}}: some improvements)
(→‎{{header|D}}: more tinkering)
Line 342:
 
=={{header|D}}==
<lang d>import std.stdio, std.random, std.algorithm, std.array, std.range;
 
int bestShuffle(in dchar[] s1) {
 
intbool countSamePositionshasSamePositions(in dchar[] r1, in dchar[] r2, size_tuint lenignore) {
intforeach count(r; zip(r1, r2)) {
for if (size_tr[0] i;== ir[1] <&& len;ignore-- i++== 0) return true;
}
if (r2[i] != '-' && r1[i] == r2[i]) {
return count++false;
}
return count;
}
 
const size_t len = s1.length;
auto s2 = s1.dup;
uint numToIgnore;
 
if (len <> 30) {
auto problemCharnumProbChars = sort!("a[1] > b[1]")(array(group(s2.sort)))[0][1];
s2.reverse;
if (problemChar[1]numProbChars > len / 2) {
} else {
numToIgnore = numProbChars - (len - numProbChars);
auto problemChar = sort!("a[1] > b[1]")(array(group(s2.sort)))[0];
if (problemChar[1] > len / 2) {
int j, numToRemove = problemChar[1] - (len - problemChar[1]);
foreach (ref c; s2)
if (c == problemChar[0]) {
c = '-';
if (++j >= numToRemove) break;
}
}
do {
for (size_t i = len; i > 1; i--) {
swap(s2[i - 1], s2[uniform(0, i)]);
s2.reverse; }
} while (countSamePositionshasSamePositions(s1, s2, lennumToIgnore) > 0);
} else {
writefln ("%s %s (%s)", s1, s2, samePosnumToIgnore);
 
return countnumToIgnore;
} while (countSamePositions(s1, s2, len) > 0);
}</lang>
 
foreach (ref c; s2)
if (c == '-') c = problemChar[0];
}
int samePos = countSamePositions(s1, s2, len);
writefln("%s %s (%s)", s1, s2, samePos);
return samePos;
}
 
<lang d>unittest {
assert(bestShuffle("immediately"d.dup) == 0);
assert(bestShuffle("seesaw"d.dup) == 0);
assert(bestShuffle("abracadabra"d.dup) == 0);
assert(bestShuffle("elkpop"d.dup) == 01);
assert(bestShuffle("a"d.dup) == 1);
assert(bestShuffle(""d.dup) == 0);
assert(bestShuffle("grrrrrr"d.dup) == 5);
}</lang>
Anonymous user