Skip to content

Instantly share code, notes, and snippets.

@code-shoily
Last active April 12, 2020 14:37
Show Gist options
  • Save code-shoily/f7f983e06c61c4f05863e74fedae3f6d to your computer and use it in GitHub Desktop.
Save code-shoily/f7f983e06c61c4f05863e74fedae3f6d to your computer and use it in GitHub Desktop.
Solve a logic puzzle with Elixir
defmodule LogicChallenge do
@type combination :: String.t()
@spec run :: combination | :error
def run() do
1..999
|> Enum.map(&to_string/1)
|> Enum.map(&String.pad_leading(&1, 3, "0"))
|> Enum.map(&String.graphemes/1)
|> Enum.filter(&check/1)
|> case do
[x] -> Enum.join(x)
_ -> :error
end
end
defp check([_, _, _] = n) do
logic_1(n) and logic_2(n) and logic_3(n) and logic_4(n) and logic_5(n)
end
defp logic_1([a, b, c]) when a in ["4", "7"] do
b not in ["1", "7"] and c not in ["1", 4]
end
defp logic_1([a, b, c]) when b in ["1", "7"] do
a not in ["4", "7"] and c not in ["1", 4]
end
defp logic_1([a, b, c]) when c in ["1", "4"] do
a not in ["4", "7"] and b not in ["1", "7"]
end
defp logic_1([_, _, _]), do: false
defp logic_2(["1", a, b]) when a not in ["8", "9"] and b not in ["8", "9"], do: true
defp logic_2([a, "8", b]) when a not in ["1", "9"] and b not in ["1", "9"], do: true
defp logic_2([a, b, "9"]) when a not in ["1", "8"] and b not in ["1", "8"], do: true
defp logic_2([_, _, _]), do: false
defp logic_3(["6", "4", x]) when x != "9", do: true
defp logic_3(["4", x, "6"]) when x != "9", do: true
defp logic_3([x, "4", "6"]) when x != "9", do: true
defp logic_3(["4", "9", x]) when x != "6", do: true
defp logic_3(["4", x, "9"]) when x != "6", do: true
defp logic_3([x, "4", "9"]) when x != "6", do: true
defp logic_3(["6", "9", x]) when x != "4", do: true
defp logic_3(["6", x, "9"]) when x != "4", do: true
defp logic_3([x, "9", "6"]) when x != "4", do: true
defp logic_3(_), do: false
defp logic_4([a, b, c]) when a in ["5", "2", "3"] or b in ["5", "2", "3"] or c in ["5", "2", 3],
do: false
defp logic_4([_, _, _]), do: true
defp logic_5([a, b, c]) when a in ["8", "6"] do
b not in ["2", "6"] and c not in ["2", "8"]
end
defp logic_5([a, b, c]) when b in ["2", "6"] do
a not in ["8", "6"] and c not in ["2", "8"]
end
defp logic_5([a, b, c]) when c in ["2", "8"] do
a not in ["8", "6"] and b not in ["2", "6"]
end
defp logic_5([_, _, _]), do: false
end
IO.puts LogicChallenge.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment