Zebra puzzle
1
var CONTENT = Hash(
2
:House => nil,
3
:Nationality => [:English, :Swedish, :Danish, :Norwegian, :German],
4
:Colour => [:Red, :Green, :White, :Blue, :Yellow],
5
:Pet => [:Dog, :Birds, :Cats, :Horse, :Zebra],
6
:Drink => [:Tea, :Coffee, :Milk, :Beer, :Water],
7
:Smoke => [:PallMall, :Dunhill, :BlueMaster, :Prince, :Blend]
8
)
9
10
func adjacent(n,i,g,e) {
11
(0..3).any {|x| (n[x]==i && g[x+1]==e) || (n[x+1]==i && g[x]==e) }
12
}
13
14
func leftof(n,i,g,e) {
15
(0..3).any {|x| n[x]==i && g[x+1]==e }
16
}
17
18
func coincident(n,i,g,e) {
19
n.indices.any {|x| n[x]==i && g[x]==e }
20
}
21
22
func solve {
23
CONTENT{:Nationality}.permutations{|*nation|
24
nation.first == :Norwegian ->
25
&& CONTENT{:Colour}.permutations {|*colour|
26
leftof(colour,:Green,colour,:White) ->
27
&& coincident(nation,:English,colour,:Red) ->
28
&& adjacent(nation,:Norwegian,colour,:Blue) ->
29
&& CONTENT{:Pet}.permutations {|*pet|
30
coincident(nation,:Swedish,pet,:Dog) ->
31
&& CONTENT{:Drink}.permutations {|*drink|
32
drink[2] == :Milk ->
33
&& coincident(nation,:Danish,drink,:Tea) ->
34
&& coincident(colour,:Green,drink,:Coffee) ->
35
&& CONTENT{:Smoke}.permutations {|*smoke|
36
coincident(smoke,:PallMall,pet,:Birds) ->
37
&& coincident(smoke,:Dunhill,colour,:Yellow) ->
38
&& coincident(smoke,:BlueMaster,drink,:Beer) ->
39
&& coincident(smoke,:Prince,nation,:German) ->
40
&& adjacent(smoke,:Blend,pet,:Cats) ->
41
&& adjacent(smoke,:Blend,drink,:Water) ->
42
&& adjacent(smoke,:Dunhill,pet,:Horse) ->
43
&& return [nation,colour,pet,drink,smoke]
44
} } } } } }
45
46
var res = solve();
47
var keys = [:House, :Nationality, :Colour, :Pet, :Drink, :Smoke]
48
var width = keys.map{ .len }
49
var fmt = width.map{|w| "%-#{w+2}s" }.join(" ")
50
say "The Zebra is owned by the man who is #{res[0][res[2].first_index(:Zebra)]}\n"
51
say (fmt % keys..., "\n", fmt % width.map{|w| "-"*w }...)
52
res[0].indices.map{|i| res.map{|a| a[i] }}.each_kv {|k,v| say fmt%(k,v...) }
Copied!

Output:

1
The Zebra is owned by the man who is German
2
3
House Nationality Colour Pet Drink Smoke
4
----- ----------- ------ --- ----- -----
5
0 Norwegian Yellow Cats Water Dunhill
6
1 Danish Blue Horse Tea Blend
7
2 English Red Birds Milk PallMall
8
3 German Green Zebra Coffee Prince
9
4 Swedish White Dog Beer BlueMaster
Copied!
Last modified 1yr ago
Copy link
Contents
Output: