Skip to content

Instantly share code, notes, and snippets.

@ynonp
Created December 13, 2020 17:52
Show Gist options
  • Save ynonp/3c7c289170ed134423881359c8e7955a to your computer and use it in GitHub Desktop.
Save ynonp/3c7c289170ed134423881359c8e7955a to your computer and use it in GitHub Desktop.
defmodule Day13 do
def read_input do
[start_time, bus_times] = File.read!("input/day13.txt")
|> String.split("\n", trim: true)
times = String.split(bus_times, ",", trim: true)
|> Enum.reject(&(&1 == "x"))
|> Enum.map(&String.to_integer/1)
[String.to_integer(start_time), times]
end
def read_input_2 do
File.read!("input/day13.txt")
|> String.split("\n", trim: true)
|> Enum.at(1)
|> String.split(",", trim: true)
end
def part1 do
[start_time, bus_times] = read_input()
IO.inspect(start_time)
IO.inspect(bus_times, charlists: :as_lists)
[id, depart_time] = bus_times
|> Enum.map(&([&1, ceil(start_time / &1) * &1]))
|> Enum.min_by(fn [_id, time] -> time end)
|> IO.inspect
IO.puts("result = #{id * (depart_time - start_time)}")
end
def find_part_2(seq, index \\ 0, result \\ 0, multiplication_so_far \\ 1)
def find_part_2([], _index, result, _multiplication_so_far) do
result
end
def find_part_2(["x" | tail], index, result, multiplication_so_far) do
find_part_2(tail, index + 1, result, multiplication_so_far)
end
def find_part_2([shead | tail], index, result, multiplication_so_far) do
IO.puts("index = #{index}; result=#{result}, mul=#{multiplication_so_far}, head=#{shead}")
head = String.to_integer(shead)
required_modulu = rem((head - index) + floor(index / head) * head, head)
next_result = (0..multiplication_so_far * head)
|> Enum.find(&(rem(&1 * multiplication_so_far + result, head) == required_modulu))
|> Kernel.*(multiplication_so_far)
|> Kernel.+(result)
find_part_2(tail, index + 1, next_result, multiplication_so_far * head)
end
def part2 do
# find_part_2(["17", "x", "13", "19"])
read_input_2
|> find_part_2()
|> IO.inspect
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment