Find the missing permutation: Difference between revisions

Content deleted Content added
→‎{{header|Racket}}: Bit vector is more appropriate type for parities.
Replaced the two D entries with one, updated
Line 346:
 
=={{header|D}}==
<lang d>import std.stdio, std.string, std.algorithm, std.array, std.range;
 
alias sum = reduce!q{a + b};
void main() {
const givenSet = "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC
BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA
DBCA DCAB"d.split().zip(repeat(true)).assocArray();
 
auto p = "ABCD"d.dup;
do {
if (p !in givenSet)
writeln("Missing permutation: ", p);
} while (p.nextPermutation());
}</lang>
{{out}}
Missing permutation: DBAC
 
===Alternative Versions===
<lang d>import std.stdio, std.string, std.algorithm, std.conv;
 
void main() {
const 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();
 
// Version 1: XORtest all the ASCII values, the uneven one getspermutations.
const permsSet = perms.zip(0.repeat).assocArray;
// flushed out; based on Perl 6 (via Go)
auto perm = cast(ubyte[4] b)perms[0].dup;
do {
foreach (perm; perms)
foreachif (i,cast(char[])perm c;!in permpermsSet)
bwriteln(cast(char[i] ^= c)perm);
} while (pperm.nextPermutation());
writeln(cast(char[])b);
 
// Version 2 : SumXOR all the ASCII values, the uneven one gets
// flushed out;. basedBased on Perl 6 (via Go).
auto sumr = perms[0].reduce!q{a + b}(); // sum row
foreachenum (i;int 0len ..= 4) {;
char[len] b = // sum columns0;
foreach (permimmutable p; perms)
const sumc = reduce!((a,b)=> text(to!int(a) + b[i]))("0",perms);
//b[] see^= how much it falls shortp[];
writeln(cast(char[])b).writeln;
write(cast(char)(sumr - to!int(sumc) % sumr));
 
// Version 3 : Sum ASCII values.
immutable rowSum = perms[0].sum;
foreach (immutable i; 0 .. len) {
immutable sumCols = sum(0, perms.transversal(i));
// See how much it falls short.
write(cast(char)(sumrrowSum - to!int(sumc)sumCols % sumrrowSum));
}
writeln();
 
// Version 34: some sort of checksum, don'tJava asktranslation.
// me:maxCode translationwill ofbe Java36.
immutable maxCode = reduce!q{a * b}(len - 1, iota(3, len + 1));
enum int len = 4;
 
int maxCode = len - 1;
foreach_reverseforeach (immutable i; 30 .. len + 1) {
immutable code = perms.map!(p code +=> perms[0].countUntil(p[i])).sum;
maxCode *= i; // maxCode will be 36
foreach (i; 0 .. len) {
int code = 0;
foreach (p; perms)
code += perms[0].countUntil(p[i]);
 
// codeCode will come up 3, 1, 0, 2 short of 36.
write(cast(char)perms[0][maxCode - code]).write;
}
}</lang>
{{out}}
<pre>DBAC
DBAC
DBAC
DBAC</pre>