Dinesman's multiple-dwelling problem: Difference between revisions

Shorter D entry
(Updated D entry)
(Shorter D entry)
Line 128:
 
=={{header|D}}==
As for flexibility: the solve functioncode isworks parameterized,with acceptingan aarbitrary lengthnumber argumentof people and a variable number of function predicates.
<lang d>import std.stdio, std.exceptionrange, std.rangealgorithm, std.algorithmmath, std.exception;
std.math, std.traits;
 
struct PermutationsLazyPermutations {
private immutable size_t num;
private uint[] seq;
Line 181 ⟶ 180:
}
}
}
 
const(uint[]) solve(T : size_t, F...)(in T len, in F predicates)
/*pure*/ nothrow {
outer:
foreach (p; Permutations(len)) {
foreach (pred; predicates)
if (!pred(p))
continue outer;
return p;
}
return null;
}
 
void main() {
//import std.traits: EnumMembers;
enum N { Baker, Cooper, Fletcher, Miller, Smith } // names
std.math,import std.traits;
enum N { Baker, Cooper, Fletcher, Miller, Smith } // names
 
alias /*immutable*/ bool function(in uint[]) pure nothrow MutablePredicateP;
alias immutable(MutablePredicate) P;
P p1 = s => s[N.Baker] != s.length-1;
P p2 = s => s[N.Cooper] != 0;
Line 207 ⟶ 195:
P p6 = s => abs(cast(int)(s[N.Cooper] - s[N.Fletcher])) != 1;
 
enum nFloorsnNames = EnumMembers!N.length;
ifimmutable (auto solpredicates = solve(nFloors, [p1, p2, p3, p4, p5, p6))];
 
writeln(map!(p => [EnumMembers!N][p])(sol));
foreach (sol; LazyPermutations(nNames))
foreachif (pred;!canFind!(p => !p(sol))(predicates))
writeln(map!(p => [EnumMembers!N][p])(sol));
}</lang>
Output:
Anonymous user