Skip to content

Instantly share code, notes, and snippets.

@JEG2
Created July 12, 2017 16:16
Show Gist options
  • Save JEG2/cbd657dcbac903a7646ef1672c4c85fb to your computer and use it in GitHub Desktop.
Save JEG2/cbd657dcbac903a7646ef1672c4c85fb to your computer and use it in GitHub Desktop.
defmodule Gunfight do
defstruct shooters: %{ }, kills: ""
@result_limit :math.pow(10, 9) |> Kernel.+(9) |> round
def new, do: %__MODULE__{ }
def point(%__MODULE__{shooters: shooters} = gunfight, pointer, "0") do
%__MODULE__{gunfight | shooters: Map.delete(shooters, pointer)}
end
def point(%__MODULE__{shooters: shooters} = gunfight, pointer, pointee) do
%__MODULE__{gunfight | shooters: Map.put(shooters, pointer, pointee)}
end
def dead?(%__MODULE__{kills: kills} = gunfight, shooter, victim) do
cond do
gunfight.shooters[shooter] == victim ->
%__MODULE__{gunfight | kills: kills <> "1"}
gunfight.shooters[shooter] == nil ->
%__MODULE__{gunfight | kills: kills <> "0"}
true ->
dead?(gunfight, gunfight.shooters[shooter], victim)
end
end
def to_result(%__MODULE__{kills: kills}) do
String.to_integer(kills, 2)
|> Integer.mod(@result_limit)
end
end
defmodule Solver do
def solve(stream) do
Enum.reduce(stream, Gunfight.new, &handle_event/2)
|> Gunfight.to_result
|> IO.inspect
end
defp handle_event("1 " <> pointing, gunfight) do
[pointer, pointee] =
pointing
|> String.split
Gunfight.point(gunfight, pointer, pointee)
end
defp handle_event("2 " <> question, gunfight) do
[shooter, victim] =
question
|> String.split
Gunfight.dead?(gunfight, shooter, victim)
end
end
System.argv
|> hd
|> File.stream!
|> Enum.drop(1)
|> Solver.solve
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment