Jump to content

Dinesman's multiple-dwelling problem: Difference between revisions

Updated D entry
(→‎{{header|D}}: fix overflow issue)
(Updated D entry)
Line 129:
=={{header|D}}==
As for flexibility: the solve function is parameterized, accepting a length argument and a variable number of function predicates.
<lang d>import std.stdio, std.exception, std.range, std.algorithm, std.math;
std.math, std.traits;
 
struct Permutations {
pure ulong fact(uint n) {
ulongprivate resultimmutable =size_t 1num;
for (uint i = 2; i <= n; i++)
result *= i;
return result;
}
 
struct LazyPermutation {
private uint[] seq;
private ulong tot;
private size_t num;
 
this (in size_t numn) {/*pure*/ nothrow
in {
enforce(num > 1, "LazyPermutation: num must be > 1");
this.seqenforce(n => array(iota(num)1, "Permutations: n must be > 1");
} body {
this.tot = fact(num);
static ulong factorial(in uint n) pure nothrow {
this.num = num;
ulong result = 1;
foreach (i; 2 .. n + 1)
result *= i;
return result;
}
 
this.seq = array(iota(n)); // not pure
this.tot = factfactorial(numn);
this.num = numn;
}
 
@property const(uint[]) front() const pure nothrow {
return seq;
}
 
@property bool empty() const pure nothrow {
return tot == 0;
}
 
void popFront() pure nothrow {
if (tot--tot > 0) {;
if (tot > 0) }{
size_t j = num - 2;
while (seq[j] > seq[j + 1]) {
j--;
}
size_t k = num - 1;
while (seq[j] > seq[k]) {
k--;
}
swap(seq[k], seq[j]);
 
Line 181 ⟶ 183:
}
 
size_tconst(uint[]) solve(T : size_t, F...)(in T len, in F predicates) {
/*pure*/ nothrow {
outer:
foreach (p; LazyPermutationPermutations(len)) {
foreach (pred; predicates)
if (!pred(p))
Line 193 ⟶ 196:
 
void main() {
enum N { Baker, Cooper, Fletcher, Miller, Smith }; // names
enum Floors = 5;
enum {Baker, Cooper, Fletcher, Miller, Smith};
 
autoalias p1bool =function(in (uint[] s){ return s[Baker] !=pure s.length-1;nothrow }MutablePredicate;
alias immutable(MutablePredicate) P;
auto p2 = (uint[] s){ return s[Cooper] != 0; };
autoP p3p1 = (uint[] s){ return s[Fletcher] != 0 &&> s[FletcherN.Baker] != s.length-1; };
autoP p4p2 = (uint[] s){ return s[Miller] => s[N.Cooper]; }!= 0;
autoP p5p3 = (uint[] s){ return=> abs(cast(int)(s[SmithN.Fletcher] -!= 0 && s[N.Fletcher])) != s.length-1; };
autoP p6p4 = (uint[] s){ return=> abs(cast(int)(s[CooperN.Miller] -> s[FletcherN.Cooper])) != 1; };
P p5 = s => abs(cast(int)(s[N.Smith] - s[N.Fletcher])) != 1;
P p6 = s => abs(cast(int)(s[N.Cooper] - s[N.Fletcher])) != 1;
 
enum nFloors = EnumMembers!N.length;
if (auto sol = solve(FloorsnFloors, p1, p2, p3, p4, p5, p6))
writeln(map!(p => [EnumMembers!N][p])(sol));
}</lang>
Output:
<pre>[2Fletcher, 1Cooper, 3Miller, 4Smith, 0Baker]</pre>
 
=={{header|Haskell}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.