This repository has been archived on 2021-06-30. You can view files and clone it, but cannot push or open issues or pull requests.
aoc2020/day_2/main.cpp

55 lines
1.6 KiB
C++
Raw Normal View History

#include <iostream>
#include <fstream>
void part1(std::ifstream& input, std::string& line) {
2020-12-02 09:17:14 +00:00
int valid_count = 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
2020-12-02 09:17:14 +00:00
std::string password = line.substr(line.find(": ") + 2);
char letter = line[fp_i + 1];
2020-12-02 09:17:14 +00:00
int low = std::stoi(line.substr(0, dash_i));
int high = std::stoi(line.substr(dash_i + 1, fp_i));
int letter_count = std::count(password.cbegin(), password.cend(), letter);
2020-12-02 09:17:14 +00:00
if (letter_count <= high && letter_count >= low) valid_count++;
}
2020-12-02 09:17:14 +00:00
std::cout << valid_count << std::endl;
}
void part2(std::ifstream& input, std::string& line) {
2020-12-02 09:17:14 +00:00
int valid_count = 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
2020-12-02 09:17:14 +00:00
std::string password = line.substr(line.find(": ") + 2);
char letter = line[fp_i + 1];
2020-12-02 09:17:14 +00:00
size_t i1 = std::stoi(line.substr(0, dash_i)) - 1;
size_t i2 = std::stoi(line.substr(dash_i + 1, fp_i)) - 1;
if (password[i1] == password[i2]) continue; // If they are the same we can skip this line
2020-12-02 09:17:14 +00:00
if (password[i1] == letter || password[i2] == letter) valid_count++;
}
2020-12-02 09:17:14 +00:00
std::cout << valid_count << 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;
2020-12-02 09:17:14 +00:00
}