From 8a82c0ed3b119d75778fed7b134fb48fffaceb13 Mon Sep 17 00:00:00 2001 From: Nick Krichevsky Date: Thu, 10 Dec 2020 00:18:54 -0500 Subject: [PATCH] Add day 10 part 1 solution --- day10/Makefile | 15 ++++++++++ day10/day10.cpp | 78 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 day10/Makefile create mode 100644 day10/day10.cpp diff --git a/day10/Makefile b/day10/Makefile new file mode 100644 index 0000000..4a611cc --- /dev/null +++ b/day10/Makefile @@ -0,0 +1,15 @@ +CC=g++ +BIN_NAME=day10 +CCFLAGS=-o $(BIN_NAME) -g -std=c++17 +LDFLAGS=-lfolly + +.PHONY: all, clean + +all: $(BIN_NAME) + +clean: + rm -f $(BIN_NAME) + +$(BIN_NAME): day10.cpp + $(CC) $(CCFLAGS) $(LDFLAGS) day10.cpp + diff --git a/day10/day10.cpp b/day10/day10.cpp new file mode 100644 index 0000000..cc943d3 --- /dev/null +++ b/day10/day10.cpp @@ -0,0 +1,78 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +constexpr auto MAX_VOLTAGE_DELTA = 3; + +std::vector readInput(const std::string &filename) { + std::vector input; + std::string line; + std::ifstream file(filename); + while (std::getline(file, line)) { + input.push_back(line); + } + + return input; +} + +/** + * Convert a vector of strings to a vector of numbers + * @param input The input for the puzzle + * @return std::vector The puzzle input as numbers + */ +std::vector convertInputToNumbers(const std::vector &input) { + std::vector converted; + converted.reserve(input.size()); + std::transform(input.cbegin(), input.cend(), std::back_inserter(converted), [](const std::string &line) { + return std::stol(line); + }); + + return converted; +} + +template +Value getOrDefault(const std::map &map, Key key, Value defaultValue) { + try { + return map.at(key); + } catch (std::out_of_range) { + return defaultValue; + } +} + +int part1(const std::vector &input) { + std::map differenceCounts; + std::vector adapters(input); + int max_voltage = *std::max_element(input.cbegin(), input.cend()) + MAX_VOLTAGE_DELTA; + adapters.insert(adapters.begin(), 0); + adapters.insert(adapters.begin(), max_voltage); + std::sort(adapters.begin(), adapters.end()); + + for (auto it = adapters.cbegin() + 1; it != adapters.cend(); it++) { + auto difference = *it - *(it - 1); + differenceCounts[difference]++; + } + + return getOrDefault(differenceCounts, 1, 0) * getOrDefault(differenceCounts, 3, 0); +} + +int main(int argc, char *argv[]) { + if (argc != 2) { + std::cerr << argv[0] << " " << std::endl; + return 1; + } + + auto input = readInput(argv[1]); + auto numericInput = convertInputToNumbers(input); + + std::cout << part1(numericInput) << std::endl; + // std::cout << part2(numbers, part1Answer) << std::endl; +}