Zebra puzzle: Difference between revisions
m
syntax highlighting fixup automation
m (→General solver with relational algebra: neaten) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 39:
=={{header|Ada}}==
Not the prettiest Ada, but it's simple and very fast. Similar to my Dinesman's code; uses enums to keep things readable.
<
procedure Zebra is
type Content is (Beer, Coffee, Milk, Tea, Water,
Line 144:
end loop; end loop;
Solve (myAlley, 0, 5); -- start at test 0 with 5 options
end Zebra;</
{{out}}
<pre>ONE: DRINK=WATER PERSON=NORWEGIAN COLOR=YELLOW SMOKE=DUNHILL PET=CAT
Line 154:
=={{header|ALGOL 68}}==
Attempts to find solutions using the rules.
<
# attempt to solve Einstein's Riddle - the Zebra puzzle #
INT unknown = 0, same = -1;
Line 294:
print( ( "solutions: ", whole( solutions, 0 ), newline ) )
END
</syntaxhighlight>
{{out}}
<pre>
Line 311:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
DIM Drink$(4), Nation$(4), Colr$(4), Smoke$(4), Animal$(4)
Drink$() = "Beer", "Coffee", "Milk", "Tea", "Water"
Line 411:
j% -= 1
ENDWHILE
= TRUE</
'''Output:'''
<pre>
Line 426:
=={{header|Bracmat}}==
<
(red green white yellow blue,(red.English.))
(dog birds cats horse zebra,(dog.?.Swede.))
Line 508:
& props$(!properties...)
& done
);</
Output:
<pre> Solution
Line 519:
=={{header|C}}==
<
#include <string.h>
Line 756:
return 0;
}</
{{out}}
<pre>% gcc -Wall -O3 -std=c99 zebra.c -o zebra && time ./zebra
Line 770:
I'll be the first to admit the following doesn't quite look like a C program. It's in fact in Perl, which outputs a C source, which in turn solves the puzzle. If you think this is long, wait till you see the C it writes.
<
use utf8;
Line 945:
# write C code. If it's ugly to you: I didn't write; Perl did.
make_c;</
output (ran as <code>perl test.pl | gcc -Wall -x c -; ./a.out</code>):<pre>
0 dunhill cats yellow water Norske
Line 959:
<!-- By Martin Freedman, 17/01/2018 -->
This is adapted from a solution to a similar problem by Peter Norvig in his [https://www.udacity.com/course/design-of-computer-programs--cs212 Udacity course CS212], originally written in Python. This is translated from [https://github.com/exercism/python/blob/master/exercises/zebra-puzzle/example.py example python solution on exercism]. This is a Generate-and-Prune Constraint Programming algorithm written with Linq. (See Benchmarks below)
<
using System.Collections.Generic;
using System.Linq;
Line 1,043:
Read();
}
}</
Produces:
<pre>
Line 1,062:
This is a different type of generate-and-prune compared to Norvig. The Norvig solution generates each attribute for 5 houses, then prunes and repeats with the next attribute. Here all houses with possible attributes are first generated and pruned to 78 candidates. The second phase proceeds over the combination of 5 houses from that 78, generating and pruning 1 house at a time. (See Benchmarks below)
<
using System.Collections.Generic;
using System.Linq;
Line 1,170:
}
}
}</
Produces
<pre>The zebra owner is German
Line 1,186:
{{works with|C sharp|C#|7.1}}
<!-- By Martin Freedman, 9/02/2018 -->
<
using System;
using System.Collections.Generic;
Line 1,271:
Read();
}
}</
Produces
<pre>The zebra owner is German
Line 1,287:
{{libheader|Microsoft Solver Foundation}}
<!-- By Martin Freedman, 19/01/2018 based on MS example code-->
<
using System.Collections.Generic;
using System.Linq;
Line 1,399:
Read();
}
}</
Produces:
<pre>
Line 1,428:
This is a modification of the C submission that uses rule classes and reduces the number of permutations evaluated.
<
#include <stdio.h>
#include <string.h>
Line 1,576:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,596:
=={{header|Clojure}}==
This solution uses the contributed package ''clojure.core.logic'' (with ''clojure.tools.macro''), a mini-Kanren based logic solver. The solution is basically the one in [http://github.com/swannodette/logic-tutorial Swannodette's logic tutorial], adapted to the problem statement here.
<
(:refer-clojure :exclude [==])
(:use [clojure.core.logic]
Line 1,638:
(println "full solution (in house order):")
(doseq [h soln] (println " " h)))
</syntaxhighlight>
{{output}}
<pre>solution count: 1
Line 1,656:
This is adapted from a solution to a similar problem by Peter Norvig in his [https://www.udacity.com/course/design-of-computer-programs--cs212 Udacity course CS212], originally written in Python but equally applicable in any language with for-comprehensions.
<
(:require [clojure.math.combinatorics :as c]))
Line 1,703:
(println (apply format "%5s %-11s %-7s %-7s %-12s %-6s"
(map #(% i) (cons inc solution)))))))
</syntaxhighlight>
{{output}}
<pre>user=> (time (zebra/-main))
Line 1,721:
=={{header|Crystal}}==
{{trans|Ruby}}
<
Nationality: %i[English Swedish Danish Norwegian German],
Colour: %i[Red Green White Blue Yellow],
Line 1,778:
end
solve_zebra_puzzle</
=={{header|Curry}}==
{{Works with|PAKCS}}
<
import Findall (findall)
Line 1,824:
main = findall $ \(hs,who) -> houses hs & H _ who Zebra _ _ `member` hs</
{{Output}} Using [http://www-ps.informatik.uni-kiel.de/~pakcs/webpakcs/main.cgi web interface].
<pre>Execution time: 180 msec. / elapsed: 180 msec.
Line 1,832:
{{trans|Ada}}
Most foreach loops in this program are static.
<
enum Content { Beer, Coffee, Milk, Tea, Water,
Line 1,926:
solve(M, Test.Drink, 5);
}</
{{out}}
<pre> One: Water Norwegian Yellow Dunhill Cat
Line 1,938:
{{trans|Python}}
This requires the module of the first D entry from the Permutations Task.
<
uint factorial(in uint n) pure nothrow @nogc @safe
Line 2,037:
writeln;
}
}</
{{out}}
<pre>Found a solution:
Line 2,052:
{{trans|PicoLisp}}
This requires the module of the second D entry from the Permutations Task.
<
import std.stdio, std.algorithm, permutations2;
Line 2,084:
nextTo(drinks, Water, smokes, Blend))
writefln("%(%10s\n%)\n", [houses, persons, drinks, pets, smokes]);
}</
{{out}}
<pre>[ Yellow, Blue, Red, Green, White]
Line 2,095:
=={{header|EchoLisp}}==
We use the '''amb''' library to solve the puzzle. The number of tries - calls to zebra-puzzle - is only 1900, before finding all solutions. Note that there are no declarations for things (cats, tea, ..) or categories (animals, drinks, ..) which are discovered when reading the constraints.
<
(lib 'hash)
(lib 'amb)
Line 2,168:
(amb-fail) ;; will ensure ALL solutions are printed
)
</syntaxhighlight>
{{out}}
<
(define (task)
(amb-run zebra-puzzle (amb-make-context) (iota 5)))
Line 2,184:
→ #f
</syntaxhighlight>
=={{header|Elixir}}==
{{trans|Ruby}}
<
defp adjacent?(n,i,g,e) do
Enum.any?(0..3, fn x ->
Line 2,261:
Smoke: ~w[PallMall Dunhill BlueMaster Prince Blend]a ]
ZebraPuzzle.solve(content)</
{{out}}
Line 2,278:
=={{header|Erlang}}==
This solution generates all houses that fits the rules for single houses, then it checks multi-house rules. It would be faster to check multi-house rules while generating the houses. I have not added this complexity since the current program takes just a few seconds.
<syntaxhighlight lang="erlang">
-module( zebra_puzzle ).
Line 2,396:
is_rule_16_ok( _House1, _House2, _House3, #house{drink=water}, #house{smoke=blend} ) -> true;
is_rule_16_ok( _House1, _House2, _House3, _House4, _House5 ) -> false.
</syntaxhighlight>
{{out}}
<pre>
Line 2,410:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM ZEBRA_PUZZLE
Line 2,516:
PRINT("Number of solutions=";SOLUTIONS%)
PRINT("Solved in ";TIMER-T1;" seconds")
END PROGRAM</
{{out}}
<pre>
Line 2,531:
=={{header|F_Sharp|F#}}==
This task uses [[Permutations_by_swapping#F.23]]
<
(*Here I solve the Zebra puzzle using Plain Changes, definitely a challenge to some campanoligist to solve it using Grandsire Doubles.
Nigel Galloway: January 27th., 2017 *)
Line 2,573:
|Some(nn) -> nn.Gz |> Array.iteri(fun n g -> if (g = G.Zebra) then printfn "\nThe man who owns a zebra is %A\n" nn.Nz.[n]); printfn "%A" nn
|None -> printfn "No solution found"
</syntaxhighlight>
{{out}}
<pre>
Line 2,586:
=={{header|FormulaOne}}==
<syntaxhighlight lang="formulaone">
// First, let's give some type-variables some values:
Nationality = Englishman | Swede | Dane | Norwegian | German
Line 2,763:
house_order(house1) = neighbour1 & house_order(house2) = neighbour2 &
house1 = house2 - 1
</syntaxhighlight>
{{out}}
<pre>
Line 2,774:
=={{header|GAP}}==
<
local i;
for i in [1..4] do
Line 2,834:
Print(cigars,"\n");
od;od;od;od;od;
</syntaxhighlight>
=={{header|Go}}==
<
import (
Line 3,130:
fmt.Println(n, "solution found")
fmt.Println(sol)
}</
{{out}}
<pre>Generated 51 valid houses
Line 3,148:
=={{header|Haskell}}==
<
import Control.Applicative ((<$>), (<*>))
Line 3,238:
leftOf p q
| (_:h:_) <- dropWhile (not . p) solution = q h
| otherwise = False</
{{out}}
<pre>House {color = Yellow, man = Nor, pet = Cats, drink = Water, smoke = Dunhill}
Line 3,253:
(a little faster version)
<
import Data.List
Line 3,312:
print [nation | (nation, _, Zebra, _, _) <- answer]
putStrLn "" )
putStrLn "No more solutions!"</
Output:
Line 3,327:
Propositions 1 .. 16 without 9,10 and15
<
cr=: (('English';'red') 0 3} ehs);<('Dane';'tea') 0 2}ehs
Line 3,339:
next=: <((<'Blend') 4 }ehs);<(<'water')2}ehs
next=: next,<((<'Blend') 4 }ehs);<(<'cats')1}ehs
next=: next,<((<'Dunhill') 4}ehs);<(<'horse')1}ehs</
'''Example'''
<
┌─────────────────┬───────────┐
│┌┬┬──────┬─────┬┐│┌┬┬┬─────┬┐│
││││coffee│green│││││││white│││
│└┴┴──────┴─────┴┘│└┴┴┴─────┴┘│
└─────────────────┴───────────┘</
Collections of all variants of the propositions:
<
hcs=:~. (A.~i.@!@#)cs,2$<ehs
hlof=:(-i.4) |."0 1 lof,3$<ehs
hnext=: ,/((i.4) |."0 1 (3$<ehs)&,)"1 ;(,,:|.)&.> next</
We start the row of houses with fixed properties 9, 10 and 15.
<
{{out}}
<
┌───────────────┬──────────┬──────────┬──────┬──────┐
│┌─────────┬┬┬┬┐│┌┬┬┬────┬┐│┌┬┬────┬┬┐│┌┬┬┬┬┐│┌┬┬┬┬┐│
││Norwegian││││││││││blue││││││milk││││││││││││││││││
│└─────────┴┴┴┴┘│└┴┴┴────┴┘│└┴┴────┴┴┘│└┴┴┴┴┘│└┴┴┴┴┘│
└───────────────┴──────────┴──────────┴──────┴──────┘</
Set of proposition variants:
<
The worker and its helper verbs
<
filter=: #~*./@:(2>#S:0)"1
compose=: [: filter f. [: ,/ select f. L:0"1"1 _
Line 3,376:
z=.(#~1=[:+/"1 (0=#)S:0"1) h=.~. h
end.
)</
{{out}}
<
┌─────────┬─────┬──────┬──────┬──────────┐
│Norwegian│cats │water │yellow│Dunhill │
Line 3,389:
├─────────┼─────┼──────┼──────┼──────────┤
│Swede │dog │beer │white │BlueMaster│
└─────────┴─────┴──────┴──────┴──────────┘</
So, the German owns the zebra.
'''Alternative'''
<br>A longer running solver by adding the zebra variants.
<
solve3=: 4 :0
Line 3,401:
z=. f^:(3>[:#(#~p"1)&>)^:_ <,:x
>"0 (#~([:*./[:;[:<@({.~:}.)\.;)"1)(#~p"1); z
)</
{{out}}
<
┌─────────┬─────┬──────┬──────┬──────────┐
│Norwegian│cats │water │yellow│Dunhill │
Line 3,414:
├─────────┼─────┼──────┼──────┼──────────┤
│Swede │dog │beer │white │BlueMaster│
└─────────┴─────┴──────┴──────┴──────────┘</
=={{header|Java}}==
Line 3,423:
* The Solver
<
import java.util.Arrays;
Line 3,853:
}
}
}</
{{out}}
<pre>
Line 3,877:
'''Part 1''': Generic filters for unification and matching
<syntaxhighlight lang="jq">
# Attempt to unify the input object with the specified object
def unify( object ):
Line 3,899:
| if $ans then .[i] = $ans else empty end
else empty
end ;</
'''Part 2''': Zebra Puzzle
<
# { "number": _, "nation": _, "owns": _, "color": _, "drinks": _, "smokes": _}
Line 3,960:
;
zebra</
{{Out}}
<div style="overflow:scroll; height:400px;">
<
[
{
Line 4,010:
real 0m0.284s
user 0m0.260s
sys 0m0.005s</
=={{header|Julia}}==
<syntaxhighlight lang="julia">
# Julia 1.0
using Combinatorics
Line 4,073:
end
</syntaxhighlight>
{{out}}
Line 4,088:
===Constraint Programming Version===
Using the rules from https://github.com/SWI-Prolog/bench/blob/master/zebra.pl
<
using JuMP
using GLPK
Line 4,163:
drinks=getindex.(m, 4),
smokes=getindex.(m, 5))
</syntaxhighlight>
{{out}}
Line 4,178:
=={{header|Kotlin}}==
<
fun nextPerm(perm: IntArray): Boolean {
Line 4,291:
val plural = if (solutions == 1) "" else "s"
println("$solutions solution$plural found")
}</
{{out}}
Line 4,311:
The Logtalk distribution includes a solution for a variant of this puzzle (here reproduced with permission):
<
/* Houses logical puzzle: who owns the zebra and who drinks water?
Line 4,388:
:- end_object.
</syntaxhighlight>
Sample query:
<
| ?- houses::(houses(S), print(S)).
h(norwegian,fox,kool,water,yellow)
Line 4,400:
S = [h(norwegian,fox,kool,water,yellow),h(ukrainian,horse,chesterfield,tea,blue),h(english,snake,winston,milk,red),h(japonese,zebra,kent,coffee,green),h(spanish,dog,lucky,juice,white)]
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Line 4,432:
This should be read as follows: Each column shows (in blocks of 5) the possible candidates of each kind (beverage, animal, smoke...)
We solve it now in a 'sudoku' way: We remove candidates iteratively until we are left with 1 candidate of each kind for each house.
<
EliminatePoss[ct_, key1_, key2_] := Module[{t = ct, poss1, poss2, poss, notposs},
poss1 = Position[t, key1];
Line 4,545:
bigtable = FixedPoint[FilterPuzzle, bigtable];
TableForm[DeleteCases[bigtable\[Transpose], Null, \[Infinity]], TableHeadings -> {Range[5], None}]</
Using the command FixedPoint, we iteratively filter out these candidates, until we are (hopefully) left with 1 candidate per kind per house.
{{out}}
Line 4,555:
=={{header|Mercury}}==
<
:- interface.
Line 4,734:
write_string("No solution found.\n", !IO)
).
</syntaxhighlight>
{{out}}
<pre>--------
Line 4,767:
parliament - japanese</pre>
=={{header|MiniZinc}}==
<syntaxhighlight lang="minizinc">
%Solve Zebra Puzzle. Nigel Galloway, August 27th., 2019
include "alldifferent.mzn";
Line 4,797:
solve satisfy;
output ["The "++show(Nz[n])++" owns the zebra"++"\n\n"++show(Nz)++"\n"++show(Iz)++"\n"++show(Gz)++"\n"++show(Ez)++"\n"++show(Lz)++"\n"];
</syntaxhighlight>
{{out}}
<pre>
Line 4,817:
be pasted into the REPL.
<syntaxhighlight lang="nial">
remove is op x xs {filter (not (x =)) xs}
Line 4,873:
abs(time - (run; time))
</syntaxhighlight>
{{out}}
Line 4,895:
Using the same order for test of criteria as in Kotlin solution.
<
type
Line 4,964:
let owner = sol.filterIt(it.pet == Zebra)[0].person
echo &"\nThe {owner} owns the zebra."</
{{out}}
Line 4,980:
=={{header|Pari/Gp}}==
<
perm(arr) = {
n=#arr;i=n-1;
Line 5,032:
for(i=1,5,printf("House:%s %6s %10s %10s %10s %10s\n",i,colors[c][i],nations[n][i],pets[p][i],drinks[d][i],smokes[s][i]));\
)))))))));
</syntaxhighlight>
{{out}}
Line 5,048:
=={{header|Perl}}==
Basically the same idea as C, though of course it's much easier to have Perl generate Perl code.
<
use utf8;
Line 5,151:
pair qw( water blend -1 1 );
$solve->();</
Incidentally, the same logic can be used to solve the dwelling problem, if somewhat awkwardly:
<
# property names and values
setprops
Line 5,174:
pair qw(cooper fletcher 4 3 2 -2 -3 -4);
$solve->();</
=={{header|Phix}}==
<!--<
<span style="color: #008080;">enum</span> <span style="color: #000000;">Colour</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">Nationality</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">Drink</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">Smoke</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">Pet</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">Colours</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"red"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"white"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"green"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"yellow"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"blue"</span><span style="color: #0000FF;">},</span>
Line 5,259:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The %s owns the Zebra\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">Nationalities</span><span style="color: #0000FF;">[</span><span style="color: #000000;">house</span><span style="color: #0000FF;">(</span><span style="color: #000000;">Pet</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"zebra"</span><span style="color: #0000FF;">)]})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 5,272:
=={{header|Picat}}==
<
main =>
Line 5,319:
writef("The %w owns the zebra\n", ZebraOwner),
writeln(L).
</syntaxhighlight>
{{out}}
<pre>
Line 5,327:
=={{header|PicoLisp}}==
<
(permute (red blue green yellow white) @House)
(left-of @House white @House green)
Line 5,367:
(be next-to (@X @A @Y @B) (right-of @X @A @Y @B))
(be next-to (@X @A @Y @B) (left-of @X @A @Y @B))</
Test:
<
(let Fmt (-8 -11 -8 -7 -11)
(tab Fmt "HOUSE" "PERSON" "DRINKS" "HAS" "SMOKES")
(mapc '(@ (pass tab Fmt))
@House @Person @Drink @Pet @Cigarettes ) ) )</
Output:
<pre>HOUSE PERSON DRINKS HAS SMOKES
Line 5,386:
In Prolog we can specify the domain by selecting elements from it, making mutually exclusive choices for efficiency:
<
select([],_).
Line 5,406:
:- ?- time(( zebra(Who, HS), maplist(writeln,HS), nl, write(Who), nl, nl, fail
; write('No more solutions.') )).</
Output:
Line 5,429:
Using extensible records, letting the houses' attributes be discovered from rules, ''not'' predetermined by a programmer (as any ''"a house has five attributes"'' solution is doing).
<
attrs( H, [N-V | R]) :- !, memberchk( N-X, H), X = V, (R = [], ! ; attrs( H, R)).
attrs( HS, AttrsL) :- maplist( attrs, HS, AttrsL).
Line 5,458:
, [[drink -water ], [smoke-'Blend' ]] % 16
] ),
in( Houses, [owns-zebra, nation-Owner]).</
[http://ideone.com/wcwXfZ Output]:
<
maplist(writeln,S),nl,writeln(Z)), false ; writeln('No More Solutions'))).
Line 5,472:
german
No More Solutions
% 263,486 inferences, 0.047 CPU in 0.063 seconds (74% CPU, 5630007 Lips)</
===Alternative version===
{{Works with|GNU Prolog}}
{{Works with|SWI Prolog}}
<
Line 5,522:
main :- findall(_, (zebra(_), nl), _), halt.
</syntaxhighlight>
{{Output}}
<pre>h(yellow,nvg,cats,water,dh)
Line 5,536:
{{Works with|SWI Prolog}}
Original source code is 'ECLiPSe ( http://eclipseclp.org/ )' example: http://eclipseclp.org/examples/zebra.ecl.txt
<
zebra :-
Line 5,590:
format(Fmt, PetNames),
format(Fmt, DrinkNames).
</syntaxhighlight>
{{Output}}
<pre>
Line 5,603:
{{trans|Clojure}}
Using 'logpy': https://github.com/logpy/logpy
<
from logpy import *
from logpy.core import lall
Line 5,677:
for line in solutions[0]:
print str(line)
</syntaxhighlight>
===Alternative Version===
{{trans|D}}
<
class Content: elems= """Beer Coffee Milk Tea Water
Line 5,781:
solve(M, Test.Drink, 5)
main()</
{{out}}
<pre> One: Water Norwegian Yellow Dunhill Cat
Line 5,790:
Runtime about 0.18 seconds.
===Alternative Version===
<
class Number:elems= "One Two Three Four Five".split()
Line 5,840:
print
main()</
Output:
<pre>Found a solution:
Line 5,853:
Using 'python-constraint': http://labix.org/python-constraint,
Original source code is 'ECLiPSe ( http://eclipseclp.org/ )' example: http://eclipseclp.org/examples/zebra.ecl.txt
<
problem = Problem()
Line 5,914:
for d in [nation, color, smoke, pet, drink]:
print("%6s: %14s%14s%14s%14s%14s" % (d[0], d[1], d[2], d[3], d[4], d[5]))
</syntaxhighlight>
Output:
<pre>Nation: Norwegian Ukrainian Englishman Spaniard Japanese
Line 5,923:
=={{header|R}}==
{{libheader|combinat}}<
library(combinat)
Line 6,004:
}
}</
{{out}}
<pre>
Line 6,019:
{{trans|Prolog}}
<
(require racklog)
Line 6,075:
(%member (list (_) Owns 'zebra (_) (_)) HS)]))
(%which (Who HS) (%zebra Who HS))</
Output:
Line 6,091:
(formerly Perl 6)
A rule driven approach:
<syntaxhighlight lang="raku"
my @facts = (
Line 6,167:
! %props.first: {%house{.key} && %house{.key} ne .value };
}
</syntaxhighlight>
{{out}}
<pre>
Line 6,183:
{{trans|BBC BASIC}}
Permutations algorithm taken from REXX
<
* Solve the Zebra Puzzle
*--------------------------------------------------------------------*/
Line 6,351:
out:
Say arg(1)
Return</
{{out}}
<pre>House Drink Nation Colour Smoke Animal
Line 6,363:
=={{header|Ruby}}==
<
Nationality: %i[English Swedish Danish Norwegian German],
Colour: %i[Red Green White Blue Yellow],
Line 6,416:
end
solve_zebra_puzzle</
{{out}}
Line 6,432:
===Another approach===
<
class String; def brk; split(/(?=[A-Z])/); end; end
men,drinks,colors,pets,smokes = "NorwegianGermanDaneSwedeEnglish
Line 6,457:
puts "The #{x.find{|y|y[0]=="Zebra"}[1]} owns the zebra.",
x.map{|y| y.map{|z| z.ljust(11)}.join}}}}}}
</syntaxhighlight>
Output:
<pre>
Line 6,470:
=={{header|Scala}}==
===Idiomatic (for comprehension)===
<
*
* It can further concluded that:
Line 6,547:
members.foreach(solution => solution.zipWithIndex.foreach(h => println(s"House ${h._2 + 1} ${h._1}")))
}
} // loc 58</
{{Out}}See it in running in your browser by [https://scalafiddle.io/sf/h5Y98te/0 ScalaFiddle (JavaScript executed in browser)] or by [https://scastie.scala-lang.org/fJZRog4xQ9aAV4D3crM1gQ Scastie (remote JVM)].{{out}}
<pre> The German is the owner of the zebra.
Line 6,559:
===Scala Alternate Version (Over-engineered)===
<
object Einstein extends App {
Line 6,642:
}
}// loc 38</
{{Out}}Experience running it in your browser by [https://scalafiddle.io/sf/hJgtjYG/1 ScalaFiddle (JavaScript executed in browser)] or by [https://scastie.scala-lang.org/ajeuRgDSQKyVv4Jd6SPfVQ Scastie (remote JVM)].
{{out}}
Line 6,657:
=={{header|Sidef}}==
{{trans|Ruby}}
<
:House => nil,
:Nationality => [:English, :Swedish, :Danish, :Norwegian, :German],
Line 6,708:
say "The Zebra is owned by the man who is #{res[0][res[2].first_index(:Zebra)]}\n"
say (fmt % keys..., "\n", fmt % width.map{|w| "-"*w }...)
res[0].indices.map{|i| res.map{|a| a[i] }}.each_kv {|k,v| say fmt%(k,v...) }</
{{out}}
<pre>
Line 6,725:
{{works with|SML/NJ}}
{{trans|C++}}(This implementation uses the search algorithm of the C++ implementation, but the rules check algorithm is different.)
<
(* Attributes and values *)
val str_attributes = Vector.fromList ["Color", "Nation", "Drink", "Pet", "Smoke"]
Line 6,975:
else print "No solution found!\n"
end
</syntaxhighlight>
{{out}}
Line 6,992:
===General solver with relational algebra===
A general solver for this type of puzzle, using relational algebra. This solver can also be used for "Dinesman's multiple-dwelling problem"
<
processor EinsteinSolver
@: [{|{}|}]; // A list of possible relations, start with one relation with an empty tuple
Line 7,088:
'No more solutions
' -> !OUT::write
</syntaxhighlight>
{{out}}
Line 7,107:
{{trans|C#}}
The streaming syntax of Tailspin lends itself naturally to this solution
<
templates permutations
when <=1> do [1] !
Line 7,160:
-> \[i]('$i;: $;'! \) -> '$... -> '$;$#10;';$#10;'
-> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 7,173:
=={{header|Tcl}}==
{{trans|Python}}
{{tcllib|struct::list}}<
# Implements the constants by binding them directly into the named procedures.
Line 7,288:
initConstants isPossible
main</
{{out}}
<pre>
Line 7,302:
=={{header|VBA}}==
{{trans|Phix}}
<
Public Enum attr
Colour = 1
Line 7,466:
Debug.Print "The " & Nationalities(perm(Nationality)(house(Pet, Zebra))) & " owns the Zebra"
Next i
End Sub</
<pre>1: yellow Norwegian water Dunhill cats
2: blue Dane tea Blend horse
Line 7,478:
=={{header|Vlang}}==
{{trans|Go}}
<
struct House {
n Nationality
Line 7,749:
println("$n solution found")
println(sol)
}</
{{out}}
Line 7,767:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<
var colors = ["Red", "Green", "White", "Yellow", "Blue"]
Line 7,881:
var solutions = fillHouses.call()
var plural = (solutions == 1) ? "" : "s"
System.print("%(solutions) solution%(plural) found")</
{{out}}
Line 7,902:
Lists are used as associated arrays rather than hash tables. With only five entries, it doesn't really matter.
<
fcn c2 { people.find(English)==houses.find(Red) }
fcn c3 { people.find(Swede)==pets.find(Dog) }
Line 7,962:
.zip(titles,names))
{ println(list.apply(names.get):fmt(title,_.xplode())) }
}</
{{out}}
<pre>
|