Add day 25 solution

master
Nick Krichevsky 2020-12-27 22:56:03 -05:00
parent aa924e801d
commit d8f47d679b
2 changed files with 98 additions and 0 deletions

15
day25/Makefile Normal file
View File

@ -0,0 +1,15 @@
CC=g++
BIN_NAME=day25
CCFLAGS=-o $(BIN_NAME) -g -O2 -std=c++17
LDFLAGS=
.PHONY: all, clean
all: $(BIN_NAME)
clean:
rm -f $(BIN_NAME)
$(BIN_NAME): day25.cpp
$(CC) $(CCFLAGS) $(LDFLAGS) day25.cpp

83
day25/day25.cpp Normal file
View File

@ -0,0 +1,83 @@
#include <cassert>
#include <fstream>
#include <functional>
#include <iostream>
#include <numeric>
#include <regex>
#include <string>
#include <tuple>
constexpr int DIVIDEND = 20201227;
constexpr int START_SUBJECT_NUMBER = 7;
std::vector<std::string> readInput(const std::string &filename) {
std::vector<std::string> input;
std::string line;
std::ifstream file(filename);
while (std::getline(file, line)) {
input.push_back(line);
}
return input;
}
/**
* @param int The puzzle input
* @return std::pair<long, long> Each public key
*/
std::pair<long, long> parseInput(const std::vector<std::string> &input) {
assert(input.size() == 2);
return std::make_pair(std::stol(input.at(0)), std::stol(input.at(1)));
}
/**
* Perform the transform
* @param subjectNumber The subject number
* @param numLoops The number of loops
* @param initValue The initial value to use
* @return long The transform
*/
long performTransform(int subjectNumber, int numLoops, int initValue = 1) {
long res = initValue;
for (int i = 0; i < numLoops; i++) {
res *= subjectNumber;
res %= DIVIDEND;
}
return res;
}
/**
* Brute force the loop size
* @param subjectNumber The subject number
* @param target The target number to stop at
* @return int THe loop size
*/
int findLoopSize(int subjectNumber, int target) {
long value = 1;
for (int loopSize = 1;; loopSize++) {
value = performTransform(subjectNumber, 1, value);
if (value == target) {
return loopSize;
}
}
}
long part1(const std::pair<int, int> &publicKeys) {
int cardLoopSize = findLoopSize(START_SUBJECT_NUMBER, publicKeys.first);
return performTransform(publicKeys.second, cardLoopSize);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
std::cerr << argv[0] << " <input_file>" << std::endl;
return 1;
}
auto input = readInput(argv[1]);
auto parsedInput = parseInput(input);
std::cout << part1(parsedInput) << std::endl;
}