From 77ef527041d04b32db91f1e77f104bd78647bc46 Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Sun, 2 Dec 2018 11:04:05 -0500 Subject: [PATCH] Day 1: Use MapSet to speed up part 2 --- lib/day1/day1.ex | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/day1/day1.ex b/lib/day1/day1.ex index 03a399f..3005aa8 100644 --- a/lib/day1/day1.ex +++ b/lib/day1/day1.ex @@ -28,6 +28,18 @@ defmodule Day1 do end) end + def first_repetition_mapset(shifts) do + shifts + |> Stream.cycle() + |> Enum.reduce_while({0, MapSet.new([0])}, fn shift, {sum, seen} -> + sum = sum + shift + cond do + sum in seen -> {:halt, sum} + true -> {:cont, {sum, MapSet.put(seen, sum)}} + end + end) + end + def parse_input() do File.read!("lib/day1/input.txt") |> String.split("\n") @@ -44,6 +56,6 @@ defmodule Day1 do def part2() do parse_input() - |> first_repetition_stream() + |> first_repetition_mapset() end end \ No newline at end of file