advent-of-code-2020/day1/day1.cpp

60 lines
1.3 KiB
C++
Raw Normal View History

2020-12-01 05:33:28 +00:00
#include <fstream>
#include <iostream>
2020-12-01 05:42:34 +00:00
#include <set>
2020-12-01 05:33:28 +00:00
#include <string>
constexpr int TARGET_NUM = 2020;
/**
* Read the input and get it as a set of integers
* @param filename The filename to read from
* @return std::set<int> A set of the numbers in the input
*/
std::set<int> readInput(const std::string &filename) {
2020-12-02 06:17:06 +00:00
std::set<int> input;
std::string line;
std::ifstream file(filename);
2020-12-01 05:33:28 +00:00
2020-12-02 06:17:06 +00:00
while (std::getline(file, line)) {
int num = std::stoi(line);
input.insert(num);
}
2020-12-01 05:33:28 +00:00
2020-12-02 06:17:06 +00:00
return input;
2020-12-01 05:33:28 +00:00
}
2020-12-01 05:42:34 +00:00
int part1(const std::set<int> &inputs) {
2020-12-02 06:17:06 +00:00
for (int num : inputs) {
int desired = TARGET_NUM - num;
if (inputs.find(desired) != inputs.end()) {
return desired * num;
}
}
throw std::runtime_error("Does not contain solution");
2020-12-01 05:33:28 +00:00
}
2020-12-01 05:42:34 +00:00
int part2(const std::set<int> &inputs) {
2020-12-02 06:17:06 +00:00
for (int num : inputs) {
for (int num2 : inputs) {
int desired = TARGET_NUM - (num + num2);
if (inputs.find(desired) != inputs.end()) {
return desired * num2 * num;
}
}
}
throw std::runtime_error("Does not contain solution");
2020-12-01 05:33:28 +00:00
}
2020-12-01 05:42:34 +00:00
int main(int argc, const char *argv[]) {
2020-12-02 06:17:06 +00:00
if (argc != 2) {
std::cerr << "./day1 <input_file>" << std::endl;
return 1;
}
std::set<int> inputs = readInput(argv[1]);
2020-12-02 06:17:06 +00:00
std::cout << part1(inputs) << std::endl;
std::cout << part2(inputs) << std::endl;
2020-12-01 05:33:28 +00:00
}