this repo has no description
at master 1.5 kB view raw
1<!-- vim:set ft=markdown: --> 2 3<!-- livebook:{"persist_outputs":true} --> 4 5# Day 3 6 7## Input 8 9```elixir 10stream = 11 File.stream!("day3.txt") 12 |> Enum.map(&String.trim/1) 13 |> Enum.map(&String.to_charlist/1) 14 15defmodule Day3 do 16 def count(list) do 17 Enum.reduce(list, List.duplicate(0, 12), fn input, acc -> 18 for {value, counter} <- Enum.zip(input, acc) do 19 case value do 20 ?1 -> counter + 1 21 ?0 -> counter 22 end 23 end 24 end) 25 end 26end 27``` 28 29```output 30{:module, Day3, <<70, 79, 82, 49, 0, 0, 7, ...>>, {:count, 1}} 31``` 32 33## Task 1 34 35```elixir 36half = div(length(stream), 2) 37 38{a, b} = 39 stream 40 |> Day3.count() 41 |> Enum.reduce({0, 0}, fn elem, {a, b} -> 42 if elem > half do 43 {a * 2 + 1, b * 2} 44 else 45 {a * 2, b * 2 + 1} 46 end 47 end) 48 49a * b 50``` 51 52```output 533847100 54``` 55 56## Task 2 57 58```elixir 59defmodule Day3.Task2 do 60 def reduce(list, cb), do: reduce(list, 0, cb) 61 62 defp reduce([elem], _, _), do: elem 63 64 defp reduce(list, at, cb) do 65 counts = Day3.count(list) 66 67 half = div(length(list), 2) 68 count = Enum.at(counts, at) 69 70 bit = 71 cond do 72 count == half and cb.(count + 1, half) -> ?1 73 count != half and cb.(count, half) -> ?1 74 true -> ?0 75 end 76 77 reduce(Enum.filter(list, &(Enum.at(&1, at) == bit)), at + 1, cb) 78 end 79end 80 81co2 = List.to_integer(Day3.Task2.reduce(stream, &</2), 2) 82o2 = List.to_integer(Day3.Task2.reduce(stream, &>/2), 2) 83 84co2 * o2 85``` 86 87```output 884105235 89```