Skip to content

Instantly share code, notes, and snippets.

@pivstone
Last active December 13, 2018 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pivstone/5ed2a8a60b8032f5c02ef8a6258a848b to your computer and use it in GitHub Desktop.
Save pivstone/5ed2a8a60b8032f5c02ef8a6258a848b to your computer and use it in GitHub Desktop.
[Elixir] adventofcode 2018 Day 2
### Part 1
data = ["kbqwtcvzgumhpwelrnaxydpfuj", "kbqwtcvzgsmhpoelryaxydiqij",
"kbqwpcvzssmhpoelgnaxydifuj", "kbqgtcvxgsmhpoalrnaxydifuj",
"kbqwtcvygsmhpoelrnaxydiaut", "kbqwtcvjgsmhpoelrnawydzfuj"]
# count the duplicated char
process = fn x ->
x
|> Enum.chunk_every(1)
|> Enum.group_by(& &1)
|> Enum.filter(fn {_, y} -> Enum.count(y) != 1 end)
|> Enum.map(fn {_, v} -> Enum.count(v) end)
|> Enum.uniq()
end
data
|> Enum.map(&to_charlist/1)
|> Enum.map(process)
|> List.flatten()
|> Enum.group_by(& &1)
# part 2
defmodule WildTier do
@wild '*'
def add(root, key, value) do
key
|> Enum.map(fn _ -> to_string(key) end)
|> Enum.with_index()
|> Enum.map(fn {k, i} -> String.slice(k, 0, i) <> "*" <> String.slice(k, (i + 1)..-1) end)
|> Enum.map(&to_charlist/1)
|> Enum.reduce(root, &(insert(&2, &1, value)))
|> insert(key, value)
end
defp insert(root, key, value) when length(key) == 1 do
Map.update(root, key, [value], &[value | &1])
end
defp insert(root, key, value) when length(key) > 1 do
[h | t] = key
sub = Map.get(root, to_charlist(<<h>>), %{})
Map.put(root, to_charlist(<<h>>), insert(sub, t, value))
end
def find?(root, _, _) when map_size(root)==0, do: nil
def find?(root, key, wild) when length(key) == 1 and wild > 0 do
Map.get(root, key, Map.get(root, @wild))
end
def find?(root, key, wild) when length(key) == 1 and wild == 0 do
Map.get(root, key, nil)
end
def find?(root, key, wild) when length(key) > 1 and wild == 0 do
[h | t] = key
if Map.has_key?(root, to_charlist(<<h>>)) do
root
|> Map.get(to_charlist(<<h>>))
|> find?(t, wild)
else
nil
end
end
def find?(root, key, wild) when length(key) > 1 and wild > 0 do
[h | t] = key
if Map.has_key?(root, to_charlist(<<h>>)) do
root
|> Map.get(to_charlist(<<h>>))
|> find?(t, wild)
else
wild = wild - 1
root
|> Map.get(@wild)
|> find?(t, wild)
end
end
end
Enum.reduce_while(data, acc, fn x, acc ->
value = WildTier.find?(acc, x, 1)
if value != nil do
{:halt, {value, x}}
else
{:cont, WildTier.add(acc, x, x)}
end
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment