-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathday_20.ex
56 lines (45 loc) · 1.36 KB
/
day_20.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
defmodule AdventOfCode.Y2015.Day20 do
@moduledoc """
--- Day 20: Infinite Elves and Infinite Houses ---
Problem Link: https://adventofcode.com/2015/day/20
Difficulty: l
Tags: slow infinite-sequence sequence
"""
alias AdventOfCode.Algorithms.Arithmetics
alias AdventOfCode.Helpers.InputReader
def input, do: InputReader.read_from_file(2015, 20)
def run(input \\ input()) do
input = String.to_integer(input)
part_1 = Task.async(fn -> run_1(input) end)
part_2 = Task.async(fn -> run_2(input) end)
{Task.await(part_1, 10_000), Task.await(part_2, 10_000)}
end
defp run_1(input) do
house_with_gifts(input, &number_of_gifts/1)
end
defp run_2(input) do
house_with_gifts(input, &number_of_gifts_below_50/1)
end
def house_with_gifts(limit, fun) do
Stream.iterate(1, &(&1 + 1))
|> Stream.map(fun)
|> Enum.take_while(fn {_, gifts} -> gifts < limit end)
|> Enum.max_by(fn {house, _} -> house end)
|> then(fn {house, _} -> house + 1 end)
end
defp number_of_gifts(house) do
gifts =
house
|> Arithmetics.divisors()
|> Enum.sum_by(&(&1 * 10))
{house, gifts}
end
defp number_of_gifts_below_50(house) do
gifts =
house
|> Arithmetics.divisors()
|> Enum.filter(fn divisor -> div(house, divisor) < 50 end)
|> Enum.sum_by(&(&1 * 11))
{house, gifts}
end
end