Skip to content

[#723] New practice exercise zebra-puzzle #753

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -2379,6 +2379,25 @@
"pattern-matching"
],
"difficulty": 9
},
{
"slug": "zebra-puzzle",
"name": "Zebra Puzzle",
"uuid": "0a561b08-6e61-4415-a3f1-e7d411a4a0e2",
"prerequisites": [
"pattern-matching",
"case",
"cond",
"if",
"enum",
"maps",
"atoms"
],
"practices": [
"enum",
"cond"
Comment on lines +2397 to +2398
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to make sure that adding these doesn't put us over the 8 exercise limit for the concept exercise @angelikatyborska

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I completely forgot about this 😱 was the limit 8 or 10? If the limit is 8, then we need to rethink 7 concepts. I think we can do that on a separate branch. I wouldn't want to block @jiegillet PR because of our previous carelessness 😅

~*~*~*~ enum ~*~*~*~

Practiced by:
10
[
  'rna-transcription',
  'resistor-color',
  'raindrops',
  'sum-of-multiples',
  'anagram',
  'hamming',
  'transpose',
  'connect',
  'minesweeper',
  'zebra-puzzle'
]

~*~*~*~ integers ~*~*~*~

Practiced by:
9
[
  'collatz-conjecture',
  'nth-prime',
  'leap',
  'all-your-base',
  'change',
  'luhn',
  'armstrong-numbers',
  'largest-series-product',
  'clock'
]

~*~*~*~ maps ~*~*~*~

Practiced by:
9
[
  'nucleotide-count',
  'scrabble-score',
  'grade-school',
  'matrix',
  'tournament',
  'binary-search-tree',
  'kindergarten-garden',
  'custom-set',
  'saddle-points'
]

~*~*~*~ pattern-matching ~*~*~*~

Practiced by:
11
[
  'bowling',
  'protein-translation',
  'triangle',
  'tournament',
  'meetup',
  'perfect-numbers',
  'queen-attack',
  'poker',
  'alphametics',
  'wordy',
  'pov'
]

~*~*~*~ ranges ~*~*~*~

Practiced by:
10
[
  'rotational-cipher',
  'pangram',
  'sum-of-multiples',
  'nth-prime',
  'isbn-verifier',
  'grains',
  'rail-fence-cipher',
  'diffie-hellman',
  'palindrome-products',
  'difference-of-squares'
]

~*~*~*~ recursion ~*~*~*~

Practiced by:
11
[
  'roman-numerals',
  'strain',
  'accumulate',
  'matching-brackets',
  'binary-search',
  'binary-search-tree',
  'prime-factors',
  'pascals-triangle',
  'spiral-matrix',
  'sieve',
  'pov'
]

~*~*~*~ regular-expressions ~*~*~*~

Practiced by:
9
[
  'word-count',
  'markdown',
  'forth',
  'acronym',
  'run-length-encoding',
  'isogram',
  'phone-number',
  'isbn-verifier',
  'grep'
]

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

],
"difficulty": 9
}
],
"foregone": [
Expand Down
27 changes: 27 additions & 0 deletions exercises/practice/zebra-puzzle/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Description

Solve the zebra puzzle.

1. There are five houses.
2. The Englishman lives in the red house.
3. The Spaniard owns the dog.
4. Coffee is drunk in the green house.
5. The Ukrainian drinks tea.
6. The green house is immediately to the right of the ivory house.
7. The Old Gold smoker owns snails.
8. Kools are smoked in the yellow house.
9. Milk is drunk in the middle house.
10. The Norwegian lives in the first house.
11. The man who smokes Chesterfields lives in the house next to the man with the fox.
12. Kools are smoked in the house next to the house where the horse is kept.
13. The Lucky Strike smoker drinks orange juice.
14. The Japanese smokes Parliaments.
15. The Norwegian lives next to the blue house.

Each of the five houses is painted a different color, and their
inhabitants are of different national extractions, own different pets,
drink different beverages and smoke different brands of cigarettes.

Which of the residents drinks water?
Who owns the zebra?

4 changes: 4 additions & 0 deletions exercises/practice/zebra-puzzle/.formatter.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]
12 changes: 12 additions & 0 deletions exercises/practice/zebra-puzzle/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"blurb": "Solve the zebra puzzle.",
"authors": ["jiegillet"],
"contributors": [],
"files": {
"solution": ["lib/zebra_puzzle.ex"],
"test": ["test/zebra_puzzle_test.exs"],
"example": [".meta/example.ex"]
},
"source": "Wikipedia",
"source_url": "https://en.wikipedia.org/wiki/Zebra_Puzzle"
}
192 changes: 192 additions & 0 deletions exercises/practice/zebra-puzzle/.meta/example.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
defmodule ZebraPuzzle do
@nationalities ~w(englishman norwegian ukrainian japanese spaniard)a
@colors ~w(red green ivory yellow blue)a
@drinks ~w(coffee tea milk orange_juice water)a
@pets ~w(dog snails fox horse zebra)a
@cigarettes ~w{old_gold kool chesterfield lucky_strike parliament}a

@doc """
Determine who drinks the water
"""
@spec drinks_water() :: atom
def drinks_water() do
[%{nationality: nationality}] =
solve_puzzle()
|> Enum.filter(fn %{drink: drink} -> drink == :water end)

nationality
end

@doc """
Determine who owns the zebra
"""
@spec owns_zebra() :: atom
def owns_zebra() do
[%{nationality: nationality}] =
solve_puzzle()
|> Enum.filter(fn %{pet: pet} -> pet == :zebra end)

nationality
end

def solve_puzzle() do
#
# Step 0: Consider all possible combinations of values
#
possibilities =
Enum.flat_map(1..5, fn order ->
Enum.flat_map(@colors, fn color ->
Enum.flat_map(@drinks, fn drink ->
Enum.flat_map(@nationalities, fn nationality ->
Enum.flat_map(@cigarettes, fn cigarette ->
Enum.map(@pets, fn pet ->
%{
order: order,
color: color,
drink: drink,
nationality: nationality,
cigarette: cigarette,
pet: pet
}
end)
end)
end)
end)
end)
end)

#
# Step 1: Add the direct constraints and filter possibilities
#
possibilities
# The Englishman lives in the red house.
|> filter_direct(:color, :red, :nationality, :englishman)
# The Spaniard owns the dog.
|> filter_direct(:nationality, :spaniard, :pet, :dog)
# Coffee is drunk in the green house.
|> filter_direct(:drink, :coffee, :color, :green)
# The Ukrainian drinks tea.
|> filter_direct(:drink, :tea, :nationality, :ukrainian)
# The Old Gold smoker owns snails.
|> filter_direct(:cigarette, :old_gold, :pet, :snails)
# Kools are smoked in the yellow house.
|> filter_direct(:cigarette, :kool, :color, :yellow)
# Milk is drunk in the middle house.
|> filter_direct(:drink, :milk, :order, 3)
# The Norwegian lives in the first house.
|> filter_direct(:nationality, :norwegian, :order, 1)
# The Lucky Strike smoker drinks orange juice.
|> filter_direct(:cigarette, :lucky_strike, :drink, :orange_juice)
# The Japanese smokes Parliaments.
|> filter_direct(:cigarette, :parliament, :nationality, :japanese)
#
# Step 2: Add indirect constraints (relations with neighbors)
#
|> filter_by_neighbors
#
# Step 3: Check if some values happen to be possibly in only one house,
# add those constraints, filter and back to step 2 until all is solved
#
|> filter_by_unique_relations
end

def filter_direct(list, field_1, value_1, field_2, value_2) do
Enum.filter(list, fn element ->
cond do
element[field_1] == value_1 and element[field_2] == value_2 -> true
element[field_1] == value_1 -> false
element[field_2] == value_2 -> false
true -> true
end
end)
end

def filter_by_neighbors(list) do
next_to = fn n -> [n - 1, n + 1] end

filtered_list =
list
# The green house is immediately to the right of the ivory house.
|> filter_indirect(:color, :green, fn n -> [n - 1] end, :color, :ivory, fn n -> [n + 1] end)
# The man who smokes Chesterfields lives in the house next to the man with the fox.
|> filter_indirect(:cigarette, :chesterfield, next_to, :pet, :fox, next_to)
# Kools are smoked in the house next to the house where the horse is kept.
|> filter_indirect(:cigarette, :kool, next_to, :pet, :horse, next_to)
# The Norwegian lives next to the blue house.
|> filter_indirect(:nationality, :norwegian, next_to, :color, :blue, next_to)

# later filters may influence earlier ones, so we loop until there is no change
if length(filtered_list) == length(list) do
list
else
filter_by_neighbors(filtered_list)
end
end

def filter_indirect(list, field_1, value_1, order_1_to_2, field_2, value_2, order_2_to_1) do
# Get all possible neighbor houses of possibilities with field_1: value_1
# Ex: find all possible house numbers that neighbor a green house
orders_2 = get_orders(list, field_1, value_1, order_1_to_2)
# Only keep possibilities with field_2: value_2 in that neighborhood
list2 = filter_neighbors(list, field_2, value_2, orders_2)

# Same from the other perspective
orders_1 = get_orders(list2, field_2, value_2, order_2_to_1)
filter_neighbors(list2, field_1, value_1, orders_1)
end

def get_orders(list, field, value, to_other_order) do
list
|> Enum.filter(&(&1[field] == value))
|> Enum.map(fn %{order: order} -> to_other_order.(order) end)
|> Enum.concat()
|> Enum.uniq()
|> Enum.filter(fn order -> 1 <= order and order <= 5 end)
end

def filter_neighbors(list, field, value, orders) do
Enum.filter(list, fn element ->
cond do
element[field] == value and element.order in orders -> true
element[field] == value -> false
length(orders) == 1 and element.order == hd(orders) -> false
true -> true
end
end)
end

def filter_by_unique_relations(list) do
# Some values happen to exist only in one particular house number
filter_parameters =
list
|> Enum.reduce(%{}, fn house, all ->
Map.update(all, house[:order], values_to_set(house), fn previous ->
Map.merge(previous, house, fn _field, val_1, val_2 -> MapSet.put(val_1, val_2) end)
end)
end)
|> Enum.map(fn {order, house} ->
house
|> Enum.filter(fn {field, value} -> field != :order and MapSet.size(value) == 1 end)
|> Enum.map(fn {field, value} -> {order, field, value |> MapSet.to_list() |> hd} end)
end)
|> Enum.concat()

# Add those values as constraints and filter
filtered_list =
filter_parameters
|> Enum.reduce(list, fn {order, f, v}, lst -> filter_direct(lst, :order, order, f, v) end)
# Run the neighbors filter again
|> filter_by_neighbors

# Loop until no more change (final solution)
if length(filtered_list) == length(list) do
filtered_list
else
filter_by_unique_relations(filtered_list)
end
end

def values_to_set(map) do
Map.new(map, fn {field, value} -> {field, MapSet.new([value])} end)
end
end
9 changes: 9 additions & 0 deletions exercises/practice/zebra-puzzle/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# This is an auto-generated file. Regular comments will be removed when this
# file is regenerated. Regenerating will not touch any manually added keys,
# so comments can be added in a "comment" key.

[16efb4e4-8ad7-4d5e-ba96-e5537b66fd42]
description = "resident who drinks water"

[084d5b8b-24e2-40e6-b008-c800da8cd257]
description = "resident who owns zebra"
15 changes: 15 additions & 0 deletions exercises/practice/zebra-puzzle/lib/zebra_puzzle.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
defmodule ZebraPuzzle do
@doc """
Determine who drinks the water
"""
@spec drinks_water() :: atom
def drinks_water() do
end

@doc """
Determine who owns the zebra
"""
@spec owns_zebra() :: atom
def owns_zebra() do
end
end
28 changes: 28 additions & 0 deletions exercises/practice/zebra-puzzle/mix.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
defmodule ZebraPuzzle.MixProject do
use Mix.Project

def project do
[
app: :zebra_puzzle,
version: "0.1.0",
# elixir: "~> 1.8",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end

# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end

# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end
2 changes: 2 additions & 0 deletions exercises/practice/zebra-puzzle/test/test_helper.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)
14 changes: 14 additions & 0 deletions exercises/practice/zebra-puzzle/test/zebra_puzzle_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
defmodule ZebraPuzzleTest do
import ZebraPuzzle
use ExUnit.Case

# @tag :pending
test "resident who drinks water" do
assert ZebraPuzzle.drinks_water() == :norwegian
end

@tag :pending
test "resident who owns zebra" do
assert ZebraPuzzle.owns_zebra() == :japanese
end
end