Jump to content

Zebra puzzle: Difference between revisions

→‎{{header|Raku}}: Make use of temp over clone. Variable renaming.
(add mercury)
(→‎{{header|Raku}}: Make use of temp over clone. Variable renaming.)
Line 6,060:
for gather solve(@houses, @facts) {
#-- output
say .[0].pairshead.sort.map(*.key.uc.fmt("%-9s")).join(' | ');
say .pairs.sort.map(*.value.fmt("%-9s")).join(' | ')
for .list;
last; # stop after first solution
Line 6,067:
}
 
#| found a solution has been found that fits all the facts
multi sub solve(@solution, @facts [ ]) {
take @solution;
}
 
#| extend athis scenario to coverfit the next fact
multi sub solve(@scenario, [ $fact, *@facts ] is copy) {
for gather choicessuppose(@scenario, |$fact) -> @houses {
solve(@$_houses, @facts)
}
}
 
#| find all possible solutions for pairs of houses with
#| lemma %a attributes, left of a house with lemma %b attributes
multi sub choicessuppose(@houses, :Left-Of(%b)!, *%a) {
for @houses {
my $idx = .<num> - 1;
if $idx > 0 && plausible(@houses[$idx-1], %a) && plausible(@houses[$idx], %b) {
mytemp @scenariohouses[$idx-1].Hash ,= @houses.clone%a;
@scenario[$idx-1]temp = %( %(@houses[$idx-1]).Hash ,= %a )b;
@scenario[$idx]take = %( %(@houses[$idx]), %b );
take @scenario;
}
}
}
 
#| suppose these houses are next to each other (left or right)
#| find all possible pairs of houses with %a attributes, either side
multi sub suppose(@houses, :Next-To(%b)!, *%a ) {
#! of a house with %b attributes
multi sub choices suppose(@houses, |%a, :NextLeft-ToOf(%b)!, *%a ) {;
choicessuppose(@houses, |%ab, :Left-Of(%ba) );
choices(@houses, |%b, :Left-Of(%a) );
}
 
#| find all possible houses that match the given attributes
multi sub choicessuppose(@houses, *%factlemma) {
for @houses.grep({plausible($_, %factlemma)}) -> $house {
my @scenario = @houses.clone;
my $idx = $house<num> - 1;
temp @scenariohouses[$idx] = %( %$house, %factlemma );
take @scenariohouses;
}
}
 
#| plausible if doesn't conflict with anything
sub plausible(%house, %attslemma) {
all! %attslemma.keys.mapfirst: { (%house{$_.key}:!exists) ||&& %house{$_.key} eqne %atts{$_}.value };
}
</lang>
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.