Skip to content

Instantly share code, notes, and snippets.

@fmcgeough
Created November 8, 2018 15:06
Show Gist options
  • Select an option

  • Save fmcgeough/159463803be2710cf34a8cd8b0d92f3a to your computer and use it in GitHub Desktop.

Select an option

Save fmcgeough/159463803be2710cf34a8cd8b0d92f3a to your computer and use it in GitHub Desktop.
defmodule MorningBrewPuzzle do
@moduledoc """
Brain Teaser from Morning Brew newsletter
Each letter stands for a unique digit that makes the arithmetic equation true. Can you solve it?
(J+O+I+N+T)^3=JOINT
"""
@doc """
Build permutations of digits from 1 to 9 (exclude 0 for simplifying a bit), slice
each element to 5 digits and unique it and then see which one solves the puzzle.
"""
def solve_puzzle do
build_list()
|> Enum.find(fn x -> is_solution?(x) end)
end
def build_list do
1..9
|> Enum.to_list()
|> permutations()
|> Enum.map(fn x -> Enum.slice(x, 0, 5) end)
|> Enum.uniq()
end
def permutations([]), do: [[]]
def permutations(list),
do: for(elem <- list, rest <- permutations(list -- [elem]), do: [elem | rest])
def is_solution?(num_list) do
val = build_number(num_list)
add_val = num_list |> add_list() |> :math.pow(3)
val == add_val
end
def add_list(num_list) do
num_list
|> Enum.reduce(0, fn x, acc -> acc + x end)
end
def build_number(num_list) do
num_list
|> Enum.join("")
|> String.to_integer()
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment