RosettaCodeData/Task/Find-the-missing-permutation/D/find-the-missing-permutation.d

44 lines
1.4 KiB
D
Raw Permalink Normal View History

2013-06-05 21:47:54 +00:00
void main() {
2014-04-02 16:56:35 +00:00
import std.stdio, std.string, std.algorithm, std.range, std.conv;
2015-02-20 00:35:01 -05:00
immutable perms = "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC
BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD
BADC BDAC CBDA DBCA DCAB".split;
2013-06-05 21:47:54 +00:00
// Version 1: test all permutations.
2015-02-20 00:35:01 -05:00
immutable permsSet = perms
.map!representation
.zip(true.repeat)
.assocArray;
auto perm = perms[0].dup.representation;
2013-06-05 21:47:54 +00:00
do {
2015-02-20 00:35:01 -05:00
if (perm !in permsSet)
writeln(perm.map!(c => char(c)));
2013-06-05 21:47:54 +00:00
} while (perm.nextPermutation);
2015-02-20 00:35:01 -05:00
// Version 2: xor all the ASCII values, the uneven one
// gets flushed out. Based on Perl 6 (via Go).
enum len = 4;
2013-06-05 21:47:54 +00:00
char[len] b = 0;
foreach (immutable p; perms)
b[] ^= p[];
b.writeln;
2015-02-20 00:35:01 -05:00
// Version 3: sum ASCII values.
2013-06-05 21:47:54 +00:00
immutable rowSum = perms[0].sum;
2014-04-02 16:56:35 +00:00
len
.iota
.map!(i => to!char(rowSum - perms.transversal(i).sum % rowSum))
.writeln;
2013-06-05 21:47:54 +00:00
2015-02-20 00:35:01 -05:00
// Version 4: a checksum, Java translation. maxCode will be 36.
2013-06-05 21:47:54 +00:00
immutable maxCode = reduce!q{a * b}(len - 1, iota(3, len + 1));
foreach (immutable i; 0 .. len) {
immutable code = perms.map!(p => perms[0].countUntil(p[i])).sum;
// Code will come up 3, 1, 0, 2 short of 36.
perms[0][maxCode - code].write;
}
}