feat: complete Advent of Code 2020-12-02

This commit is contained in:
Rekai Nyangadzayi Musuka 2020-12-02 03:01:52 -06:00
parent 074df8a840
commit abf4233189
4 changed files with 1071 additions and 0 deletions

3
day_2/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
/.idea
/cmake-build-debug

6
day_2/CMakeLists.txt Normal file
View File

@ -0,0 +1,6 @@
cmake_minimum_required(VERSION 3.19)
project(day_2)
set(CMAKE_CXX_STANDARD 20)
add_executable(day_2 main.cpp)

1000
day_2/input.txt Normal file

File diff suppressed because it is too large Load Diff

62
day_2/main.cpp Normal file
View File

@ -0,0 +1,62 @@
#include <iostream>
#include <fstream>
void part1(std::ifstream& input, std::string& line) {
int num_valid = 0;
while (std::getline(input, line)) {
size_t fp_i = line.find(' '); // Index of the first space in line
size_t dash_i = line.find('-'); // Index of the only dash in line
size_t ss_i = line.substr(fp_i + 1).find(' ') + fp_i + 1; // Index of the second space in line
std::string range = line.substr(0, fp_i); // "9-11": the range that we're looking for letter to be in
std::string password = line.substr(ss_i + 1);
char letter = line[fp_i + 1];
int low = std::stoi(range.substr(0, dash_i));
int high = std::stoi(range.substr(dash_i + 1));
int letter_count = std::count(password.cbegin(), password.cend(), letter);
if (letter_count <= high && letter_count >= low) num_valid++;
}
std::cout << num_valid << std::endl;
}
void part2(std::ifstream& input, std::string& line) {
int num_valid = 0;
while(std::getline(input, line)) {
size_t fp_i = line.find(' '); // Index of the first space in line
size_t dash_i = line.find('-'); // Index of the only dash in line
size_t ss_index = line.substr(fp_i + 1).find(' ') + fp_i + 1; // Index of the second space in line
std::string range = line.substr(0, fp_i); // "9-11": We will check indexes 9 and 11
std::string password = line.substr(ss_index + 1);
char letter = line[fp_i + 1];
size_t i1 = std::stoi(range.substr(0, dash_i)) - 1;
size_t i2 = std::stoi(range.substr(dash_i + 1)) - 1;
if (password[i1] == password[i2]) continue; // If they are the same we can skip this line
if (password[i1] == letter || password[i2] == letter) num_valid++;
}
std::cout << num_valid << std::endl;
}
int main() {
std::ifstream input("../input.txt");
std::string line;
part1(input, line);
input.clear(); // clear EOF flag
input.seekg(0);
part2(input, line);
return 0;
}