Zebra puzzle: Difference between revisions

m
syntax highlighting fixup automation
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.
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
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;</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="algol68">BEGIN
# attempt to solve Einstein's Riddle - the Zebra puzzle #
INT unknown = 0, same = -1;
Line 294:
print( ( "solutions: ", whole( solutions, 0 ), newline ) )
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 311:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> REM The names (only used for printing the results):
DIM Drink$(4), Nation$(4), Colr$(4), Smoke$(4), Animal$(4)
Drink$() = "Beer", "Coffee", "Milk", "Tea", "Water"
Line 411:
j% -= 1
ENDWHILE
= TRUE</langsyntaxhighlight>
'''Output:'''
<pre>
Line 426:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( (English Swede Dane Norwegian German,)
(red green white yellow blue,(red.English.))
(dog birds cats horse zebra,(dog.?.Swede.))
Line 508:
& props$(!properties...)
& done
);</langsyntaxhighlight>
Output:
<pre> Solution
Line 519:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
 
Line 756:
 
return 0;
}</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use utf8;
Line 945:
 
# write C code. If it's ugly to you: I didn't write; Perl did.
make_c;</langsyntaxhighlight>
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)
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,043:
Read();
}
}</langsyntaxhighlight>
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)
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,170:
}
}
}</langsyntaxhighlight>
Produces
<pre>The zebra owner is German
Line 1,186:
{{works with|C sharp|C#|7.1}}
<!-- By Martin Freedman, 9/02/2018 -->
<langsyntaxhighlight lang="csharp">using Amb;
using System;
using System.Collections.Generic;
Line 1,271:
Read();
}
}</langsyntaxhighlight>
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-->
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,399:
Read();
}
}</langsyntaxhighlight>
Produces:
<pre>
Line 1,428:
This is a modification of the C submission that uses rule classes and reduces the number of permutations evaluated.
 
<langsyntaxhighlight lang="cpp">
#include <stdio.h>
#include <string.h>
Line 1,576:
return 0;
}
</syntaxhighlight>
</lang>
{{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.
<langsyntaxhighlight lang="clojure">(ns zebra.core
(:refer-clojure :exclude [==])
(:use [clojure.core.logic]
Line 1,638:
(println "full solution (in house order):")
(doseq [h soln] (println " " h)))
</syntaxhighlight>
</lang>
{{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.
 
<langsyntaxhighlight lang="clojure">(ns zebra
(:require [clojure.math.combinatorics :as c]))
 
Line 1,703:
(println (apply format "%5s %-11s %-7s %-7s %-12s %-6s"
(map #(% i) (cons inc solution)))))))
</syntaxhighlight>
</lang>
{{output}}
<pre>user=> (time (zebra/-main))
Line 1,721:
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">CONTENT = {House: [""],
Nationality: %i[English Swedish Danish Norwegian German],
Colour: %i[Red Green White Blue Yellow],
Line 1,778:
end
 
solve_zebra_puzzle</langsyntaxhighlight>
 
=={{header|Curry}}==
{{Works with|PAKCS}}
<langsyntaxhighlight lang="curry">import Constraint (allC, anyC)
import Findall (findall)
 
Line 1,824:
 
 
main = findall $ \(hs,who) -> houses hs & H _ who Zebra _ _ `member` hs</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="d">import std.stdio, std.traits, std.algorithm, std.math;
 
enum Content { Beer, Coffee, Milk, Tea, Water,
Line 1,926:
 
solve(M, Test.Drink, 5);
}</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="d">import std.stdio, std.math, std.traits, std.typecons, std.typetuple, permutations1;
 
uint factorial(in uint n) pure nothrow @nogc @safe
Line 2,037:
writeln;
}
}</langsyntaxhighlight>
{{out}}
<pre>Found a solution:
Line 2,052:
{{trans|PicoLisp}}
This requires the module of the second D entry from the Permutations Task.
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, permutations2;
 
Line 2,084:
nextTo(drinks, Water, smokes, Blend))
writefln("%(%10s\n%)\n", [houses, persons, drinks, pets, smokes]);
}</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="scheme">
(lib 'hash)
(lib 'amb)
Line 2,168:
(amb-fail) ;; will ensure ALL solutions are printed
)
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="scheme">
(define (task)
(amb-run zebra-puzzle (amb-make-context) (iota 5)))
Line 2,184:
→ #f
 
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule ZebraPuzzle do
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)</langsyntaxhighlight>
 
{{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">
<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>
</lang>
{{out}}
<pre>
Line 2,410:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM ZEBRA_PUZZLE
 
Line 2,516:
PRINT("Number of solutions=";SOLUTIONS%)
PRINT("Solved in ";TIMER-T1;" seconds")
END PROGRAM</langsyntaxhighlight>
{{out}}
<pre>
Line 2,531:
=={{header|F_Sharp|F#}}==
This task uses [[Permutations_by_swapping#F.23]]
<langsyntaxhighlight lang="fsharp">
(*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>
</lang>
{{out}}
<pre>
Line 2,586:
 
=={{header|FormulaOne}}==
<syntaxhighlight lang="formulaone">
<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>
</lang>
{{out}}
<pre>
Line 2,774:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">leftOf :=function(setA, vA, setB, vB)
local i;
for i in [1..4] do
Line 2,834:
Print(cigars,"\n");
od;od;od;od;od;
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 3,130:
fmt.Println(n, "solution found")
fmt.Println(sol)
}</langsyntaxhighlight>
{{out}}
<pre>Generated 51 valid houses
Line 3,148:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">module Main where
 
import Control.Applicative ((<$>), (<*>))
Line 3,238:
leftOf p q
| (_:h:_) <- dropWhile (not . p) solution = q h
| otherwise = False</langsyntaxhighlight>
{{out}}
<pre>House {color = Yellow, man = Nor, pet = Cats, drink = Water, smoke = Dunhill}
Line 3,253:
(a little faster version)
 
<langsyntaxhighlight lang="haskell">import Control.Monad
import Data.List
 
Line 3,312:
print [nation | (nation, _, Zebra, _, _) <- answer]
putStrLn "" )
putStrLn "No more solutions!"</langsyntaxhighlight>
 
Output:
Line 3,327:
 
Propositions 1 .. 16 without 9,10 and15
<langsyntaxhighlight lang="j">ehs=: 5$a:
 
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</langsyntaxhighlight>
'''Example'''
<langsyntaxhighlight lang="j"> lof
┌─────────────────┬───────────┐
│┌┬┬──────┬─────┬┐│┌┬┬┬─────┬┐│
││││coffee│green│││││││white│││
│└┴┴──────┴─────┴┘│└┴┴┴─────┴┘│
└─────────────────┴───────────┘</langsyntaxhighlight>
 
Collections of all variants of the propositions:
<langsyntaxhighlight lang="j">hcr=: (<ehs),. (A.~i.@!@#)cr
hcs=:~. (A.~i.@!@#)cs,2$<ehs
hlof=:(-i.4) |."0 1 lof,3$<ehs
hnext=: ,/((i.4) |."0 1 (3$<ehs)&,)"1 ;(,,:|.)&.> next</langsyntaxhighlight>
 
We start the row of houses with fixed properties 9, 10 and 15.
<langsyntaxhighlight lang="j">houses=: ((<'Norwegian') 0}ehs);((<'blue') 3 }ehs);((<'milk') 2}ehs);ehs;<ehs</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="j"> houses
┌───────────────┬──────────┬──────────┬──────┬──────┐
│┌─────────┬┬┬┬┐│┌┬┬┬────┬┐│┌┬┬────┬┬┐│┌┬┬┬┬┐│┌┬┬┬┬┐│
││Norwegian││││││││││blue││││││milk││││││││││││││││││
│└─────────┴┴┴┴┘│└┴┴┴────┴┘│└┴┴────┴┴┘│└┴┴┴┴┘│└┴┴┴┴┘│
└───────────────┴──────────┴──────────┴──────┴──────┘</langsyntaxhighlight>
Set of proposition variants:
<langsyntaxhighlight lang="j">constraints=: hcr;hcs;hlof;<hnext</langsyntaxhighlight>
The worker and its helper verbs
<langsyntaxhighlight lang="j">select=: ~.@(,: #~ ,&(0~:#))
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.
)</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="j"> >"0 houses solve constraints
┌─────────┬─────┬──────┬──────┬──────────┐
│Norwegian│cats │water │yellow│Dunhill │
Line 3,389:
├─────────┼─────┼──────┼──────┼──────────┤
│Swede │dog │beer │white │BlueMaster│
└─────────┴─────┴──────┴──────┴──────────┘</langsyntaxhighlight>
So, the German owns the zebra.
 
'''Alternative'''
<br>A longer running solver by adding the zebra variants.
<langsyntaxhighlight lang="j">zebra=: (-i.5)|."0 1 (<(<'zebra') 1}ehs),4$<ehs
 
solve3=: 4 :0
Line 3,401:
z=. f^:(3>[:#(#~p"1)&>)^:_ <,:x
>"0 (#~([:*./[:;[:<@({.~:}.)\.;)"1)(#~p"1); z
)</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="j"> houses solve3 constraints,<zebra
┌─────────┬─────┬──────┬──────┬──────────┐
│Norwegian│cats │water │yellow│Dunhill │
Line 3,414:
├─────────┼─────┼──────┼──────┼──────────┤
│Swede │dog │beer │white │BlueMaster│
└─────────┴─────┴──────┴──────┴──────────┘</langsyntaxhighlight>
 
=={{header|Java}}==
Line 3,423:
* The Solver
 
<langsyntaxhighlight Javalang="java">package org.rosettacode.zebra;
 
import java.util.Arrays;
Line 3,853:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,877:
 
'''Part 1''': Generic filters for unification and matching
<syntaxhighlight lang="jq">
<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 ;</langsyntaxhighlight>
'''Part 2''': Zebra Puzzle
<langsyntaxhighlight lang="jq"># Each house is a JSON object of the form:
# { "number": _, "nation": _, "owns": _, "color": _, "drinks": _, "smokes": _}
 
Line 3,960:
;
zebra</langsyntaxhighlight>
{{Out}}
<div style="overflow:scroll; height:400px;">
<langsyntaxhighlight lang="sh">$ time jq -n -f zebra.jq
[
{
Line 4,010:
real 0m0.284s
user 0m0.260s
sys 0m0.005s</langsyntaxhighlight></div>
 
=={{header|Julia}}==
 
<syntaxhighlight lang="julia">
<lang Julia>
# Julia 1.0
using Combinatorics
Line 4,073:
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,088:
===Constraint Programming Version===
Using the rules from https://github.com/SWI-Prolog/bench/blob/master/zebra.pl
<langsyntaxhighlight Julialang="julia"># Julia 1.4
using JuMP
using GLPK
Line 4,163:
drinks=getindex.(m, 4),
smokes=getindex.(m, 5))
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,178:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.3
 
fun nextPerm(perm: IntArray): Boolean {
Line 4,291:
val plural = if (solutions == 1) "" else "s"
println("$solutions solution$plural found")
}</langsyntaxhighlight>
 
{{out}}
Line 4,311:
The Logtalk distribution includes a solution for a variant of this puzzle (here reproduced with permission):
 
<langsyntaxhighlight lang="logtalk">
/* Houses logical puzzle: who owns the zebra and who drinks water?
 
Line 4,388:
 
:- end_object.
</syntaxhighlight>
</lang>
 
Sample query:
<langsyntaxhighlight lang="text">
| ?- 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>
</lang>
 
=={{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.
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[EliminatePoss, FilterPuzzle]
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}]</langsyntaxhighlight>
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}}==
<langsyntaxhighlight Mercurylang="mercury">:- module zebra.
:- interface.
 
Line 4,734:
write_string("No solution found.\n", !IO)
).
</syntaxhighlight>
</lang>
{{out}}
<pre>--------
Line 4,767:
parliament - japanese</pre>
=={{header|MiniZinc}}==
<syntaxhighlight lang="minizinc">
<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>
</lang>
{{out}}
<pre>
Line 4,817:
be pasted into the REPL.
 
<syntaxhighlight lang="nial">
<lang Nial>
remove is op x xs {filter (not (x =)) xs}
 
Line 4,873:
 
abs(time - (run; time))
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,895:
Using the same order for test of criteria as in Kotlin solution.
 
<langsyntaxhighlight Nimlang="nim">import algorithm, strformat, sequtils
 
type
Line 4,964:
 
let owner = sol.filterIt(it.pet == Zebra)[0].person
echo &"\nThe {owner} owns the zebra."</langsyntaxhighlight>
 
{{out}}
Line 4,980:
 
=={{header|Pari/Gp}}==
<langsyntaxhighlight lang="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>
</lang>
 
{{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.
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use utf8;
Line 5,151:
pair qw( water blend -1 1 );
 
$solve->();</langsyntaxhighlight>
 
Incidentally, the same logic can be used to solve the dwelling problem, if somewhat awkwardly:
<langsyntaxhighlight lang="perl">...
# property names and values
setprops
Line 5,174:
pair qw(cooper fletcher 4 3 2 -2 -3 -4);
 
$solve->();</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 5,272:
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">import cp.
 
main =>
Line 5,319:
writef("The %w owns the zebra\n", ZebraOwner),
writeln(L).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,327:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(be match (@House @Person @Drink @Pet @Cigarettes)
(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))</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">(pilog '((match @House @Person @Drink @Pet @Cigarettes))
(let Fmt (-8 -11 -8 -7 -11)
(tab Fmt "HOUSE" "PERSON" "DRINKS" "HAS" "SMOKES")
(mapc '(@ (pass tab Fmt))
@House @Person @Drink @Pet @Cigarettes ) ) )</langsyntaxhighlight>
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:
 
<langsyntaxhighlight Prologlang="prolog">select([A|As],S):- select(A,S,S1),select(As,S1).
select([],_).
Line 5,406:
 
:- ?- time(( zebra(Who, HS), maplist(writeln,HS), nl, write(Who), nl, nl, fail
; write('No more solutions.') )).</langsyntaxhighlight>
 
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).
 
<langsyntaxhighlight Prologlang="prolog">% attribute store is 'Name - Value' pairs with unique names
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]).</langsyntaxhighlight>
[http://ideone.com/wcwXfZ Output]:
<langsyntaxhighlight Prologlang="prolog">?- time(( zebra(Z,HS), (maplist(length,HS,_) -> maplist(sort,HS,S),
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)</langsyntaxhighlight>
 
===Alternative version===
{{Works with|GNU Prolog}}
{{Works with|SWI Prolog}}
<langsyntaxhighlight lang="prolog">:- initialization(main).
 
 
Line 5,522:
 
main :- findall(_, (zebra(_), nl), _), halt.
</syntaxhighlight>
</lang>
{{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
<langsyntaxhighlight lang="prolog">:- use_module(library(clpfd)).
 
zebra :-
Line 5,590:
format(Fmt, PetNames),
format(Fmt, DrinkNames).
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 5,603:
{{trans|Clojure}}
Using 'logpy': https://github.com/logpy/logpy
<langsyntaxhighlight lang="python">
from logpy import *
from logpy.core import lall
Line 5,677:
for line in solutions[0]:
print str(line)
</syntaxhighlight>
</lang>
 
===Alternative Version===
{{trans|D}}
<langsyntaxhighlight lang="python">import psyco; psyco.full()
 
class Content: elems= """Beer Coffee Milk Tea Water
Line 5,781:
solve(M, Test.Drink, 5)
 
main()</langsyntaxhighlight>
{{out}}
<pre> One: Water Norwegian Yellow Dunhill Cat
Line 5,790:
Runtime about 0.18 seconds.
===Alternative Version===
<langsyntaxhighlight lang="python">from itertools import permutations
 
class Number:elems= "One Two Three Four Five".split()
Line 5,840:
print
 
main()</langsyntaxhighlight>
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
<langsyntaxhighlight lang="python">from constraint import *
 
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>
</lang>
Output:
<pre>Nation: Norwegian Ukrainian Englishman Spaniard Japanese
Line 5,923:
 
=={{header|R}}==
{{libheader|combinat}}<langsyntaxhighlight Rlang="r">
 
library(combinat)
Line 6,004:
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 6,019:
{{trans|Prolog}}
 
<langsyntaxhighlight lang="racket">#lang racket
 
(require racklog)
Line 6,075:
(%member (list (_) Owns 'zebra (_) (_)) HS)]))
 
(%which (Who HS) (%zebra Who HS))</langsyntaxhighlight>
 
Output:
Line 6,091:
(formerly Perl 6)
A rule driven approach:
<syntaxhighlight lang="raku" perl6line>my Hash @houses = (1 .. 5).map: { %(:num($_)) }; # 1 there are five houses
 
my @facts = (
Line 6,167:
! %props.first: {%house{.key} && %house{.key} ne .value };
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,183:
{{trans|BBC BASIC}}
Permutations algorithm taken from REXX
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* Solve the Zebra Puzzle
*--------------------------------------------------------------------*/
Line 6,351:
out:
Say arg(1)
Return</langsyntaxhighlight>
{{out}}
<pre>House Drink Nation Colour Smoke Animal
Line 6,363:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">CONTENT = { House: '',
Nationality: %i[English Swedish Danish Norwegian German],
Colour: %i[Red Green White Blue Yellow],
Line 6,416:
end
 
solve_zebra_puzzle</langsyntaxhighlight>
 
{{out}}
Line 6,432:
 
===Another approach===
<langsyntaxhighlight lang="ruby">
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>
</lang>
Output:
<pre>
Line 6,470:
=={{header|Scala}}==
===Idiomatic (for comprehension)===
<langsyntaxhighlight Scalalang="scala">/* Note to the rules:
*
* 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</langsyntaxhighlight>
{{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)===
<langsyntaxhighlight lang="scala">import scala.util.Try
 
object Einstein extends App {
Line 6,642:
}
 
}// loc 38</langsyntaxhighlight>
{{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}}
<langsyntaxhighlight lang="ruby">var CONTENT = Hash(
: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...) }</langsyntaxhighlight>
{{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.)
<langsyntaxhighlight lang="sml">
(* Attributes and values *)
val str_attributes = Vector.fromList ["Color", "Nation", "Drink", "Pet", "Smoke"]
Line 6,975:
else print "No solution found!\n"
end
</syntaxhighlight>
</lang>
 
{{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"
<langsyntaxhighlight lang="tailspin">
processor EinsteinSolver
@: [{|{}|}]; // A list of possible relations, start with one relation with an empty tuple
Line 7,088:
'No more solutions
' -> !OUT::write
</syntaxhighlight>
</lang>
 
{{out}}
Line 7,107:
{{trans|C#}}
The streaming syntax of Tailspin lends itself naturally to this solution
<langsyntaxhighlight lang="tailspin">
templates permutations
when <=1> do [1] !
Line 7,160:
-> \[i]('$i;: $;'! \) -> '$... -> '$;$#10;';$#10;'
-> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 7,173:
=={{header|Tcl}}==
{{trans|Python}}
{{tcllib|struct::list}}<langsyntaxhighlight lang="tcl">package require struct::list
 
# Implements the constants by binding them directly into the named procedures.
Line 7,288:
 
initConstants isPossible
main</langsyntaxhighlight>
{{out}}
<pre>
Line 7,302:
=={{header|VBA}}==
{{trans|Phix}}
<langsyntaxhighlight lang="vb">Option Base 1
Public Enum attr
Colour = 1
Line 7,466:
Debug.Print "The " & Nationalities(perm(Nationality)(house(Pet, Zebra))) & " owns the Zebra"
Next i
End Sub</langsyntaxhighlight>{{out}}
<pre>1: yellow Norwegian water Dunhill cats
2: blue Dane tea Blend horse
Line 7,478:
=={{header|Vlang}}==
{{trans|Go}}
<langsyntaxhighlight lang="vlang">type HouseSet = []House
struct House {
n Nationality
Line 7,749:
println("$n solution found")
println(sol)
}</langsyntaxhighlight>
 
{{out}}
Line 7,767:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "/fmt" for 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")</langsyntaxhighlight>
 
{{out}}
Line 7,902:
 
Lists are used as associated arrays rather than hash tables. With only five entries, it doesn't really matter.
<langsyntaxhighlight lang="zkl">var people,drinks,houses,smokes,pets; // lists treated as associated arrays
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())) }
}</langsyntaxhighlight>
{{out}}
<pre>
10,339

edits