From 7b67ec3c39324b9eac7c8341fe5fdddc0b78afe2 Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Sun, 6 Dec 2020 11:55:10 -0500 Subject: [PATCH] Day 6 improved --- lib/day6/day6.ex | 34 ++++++++++++---------------------- 1 file changed, 12 insertions(+), 22 deletions(-) diff --git a/lib/day6/day6.ex b/lib/day6/day6.ex index 80ee0a6..68707dd 100644 --- a/lib/day6/day6.ex +++ b/lib/day6/day6.ex @@ -18,35 +18,25 @@ defmodule Day6 do """ def part1(example \\ false) do - parse_input(example) - |> Enum.map(&questions_with_any_yes/1) - |> Enum.map(&MapSet.size/1) - |> Enum.sum() + get_answer(example, &MapSet.union/2) end def part2(example \\ false) do - parse_input(example) - |> Enum.map(&questions_with_all_yes/1) + get_answer(example, &MapSet.intersection/2) + end + + def get_answer(example, combiner) do + if(example, do: @example, else: File.read!("lib/day6/input.txt")) + |> String.trim() + |> String.split("\n\n") + |> Enum.map(fn group -> answers_to_count(group, combiner) end) |> Enum.map(&MapSet.size/1) |> Enum.sum() end - def parse_input(example) do - if(example, do: @example, else: File.read!("lib/day6/input.txt")) - |> String.trim() - |> String.split("\n\n") - end - - def questions_with_any_yes(str) do - str - |> String.replace(~r/\s/, "") - |> String.to_charlist() - |> MapSet.new() - end - - def questions_with_all_yes(str) do + def answers_to_count(group, combiner) do people = - str + group |> String.split("\n") |> Enum.map(fn person -> person @@ -56,6 +46,6 @@ defmodule Day6 do people |> Enum.drop(1) - |> Enum.reduce(List.first(people), &MapSet.intersection/2) + |> Enum.reduce(List.first(people), combiner) end end