first three days
This commit is contained in:
71
day1/src/main.cpp
Normal file
71
day1/src/main.cpp
Normal file
@@ -0,0 +1,71 @@
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
struct Instruction {
|
||||
const char direction;
|
||||
const int value;
|
||||
};
|
||||
|
||||
std::vector<Instruction> parse_input_file(const std::string &path) {
|
||||
std::ifstream file;
|
||||
std::vector<Instruction> vec;
|
||||
std::string line;
|
||||
|
||||
file.open(path);
|
||||
if (file.is_open()) {
|
||||
while (std::getline(file, line)) {
|
||||
auto instr = line.at(0);
|
||||
int value = std::stoi(line.substr(1));
|
||||
vec.emplace_back(Instruction{instr, value});
|
||||
}
|
||||
file.close();
|
||||
} else {
|
||||
std::cout << "Failed to open file: " << path << std::endl;
|
||||
}
|
||||
|
||||
return vec;
|
||||
}
|
||||
|
||||
std::tuple<int, int> doit(const std::vector<Instruction> &instructions) {
|
||||
int dial_val = 50;
|
||||
int zero_counter_part1 = 0;
|
||||
int zero_counter_part2 = 0;
|
||||
for (const auto &instr : instructions) {
|
||||
for (int i = 0; i < instr.value; i++) {
|
||||
if (instr.direction == 'L') {
|
||||
dial_val--;
|
||||
} else {
|
||||
dial_val++;
|
||||
}
|
||||
|
||||
if (dial_val > 99)
|
||||
dial_val = 0;
|
||||
else if (dial_val < 0)
|
||||
dial_val = 99;
|
||||
if (dial_val == 0)
|
||||
zero_counter_part2 += 1;
|
||||
}
|
||||
if (dial_val == 0)
|
||||
zero_counter_part1 += 1;
|
||||
|
||||
std::cout << "dial_val: " << dial_val << std::endl;
|
||||
}
|
||||
return std::make_tuple(zero_counter_part1, zero_counter_part2);
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
if (argc < 2) {
|
||||
std::cout << "One argument required: input txt" << std::endl;
|
||||
}
|
||||
|
||||
auto instructions = parse_input_file(argv[1]);
|
||||
|
||||
auto num_zeros = doit(instructions);
|
||||
|
||||
std::cout << "Number of times dial hits zero (part 1): "
|
||||
<< std::get<0>(num_zeros) << std::endl;
|
||||
std::cout << "Number of times dial hits zero (part 2): "
|
||||
<< std::get<1>(num_zeros) << std::endl;
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user