first three days
This commit is contained in:
90
day3/src/main.cpp
Normal file
90
day3/src/main.cpp
Normal file
@@ -0,0 +1,90 @@
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <numeric>
|
||||
#include <vector>
|
||||
|
||||
int do_part_1(const std::string &line) {
|
||||
int greatest = -1;
|
||||
int second_greatest = -1;
|
||||
for (size_t i = 0; i < line.length(); i++) {
|
||||
char c = line[i];
|
||||
int j = static_cast<int>(c - '0');
|
||||
if (j > greatest && i < (line.length() - 1)) {
|
||||
second_greatest = -1;
|
||||
greatest = j;
|
||||
} else if (j > second_greatest) {
|
||||
second_greatest = j;
|
||||
}
|
||||
}
|
||||
|
||||
auto joint = std::to_string(greatest) + std::to_string(second_greatest);
|
||||
|
||||
return std::stoi(joint);
|
||||
}
|
||||
|
||||
int find_highest_leading(std::string &line, int len) {
|
||||
int highest_leading = -1;
|
||||
int highest_pos = -1;
|
||||
for (size_t i = 0; i < (line.length() - len + 1); i++) {
|
||||
int j = static_cast<int>(line[i] - '0');
|
||||
if (j > highest_leading) {
|
||||
highest_leading = j;
|
||||
highest_pos = i;
|
||||
}
|
||||
}
|
||||
line = line.substr(highest_pos + 1);
|
||||
return highest_leading;
|
||||
}
|
||||
|
||||
long do_part_2(std::string line) {
|
||||
std::string highest_seq = "";
|
||||
for (int i = 12; i > 0; i--) {
|
||||
std::cout << "line " << line << std::endl;
|
||||
int highest_leading = find_highest_leading(line, i);
|
||||
highest_seq += std::to_string(highest_leading);
|
||||
}
|
||||
return std::stol(highest_seq);
|
||||
}
|
||||
|
||||
std::tuple<long, long> parse_input_file(const std::string &path) {
|
||||
std::ifstream file;
|
||||
std::string line;
|
||||
|
||||
file.open(path);
|
||||
long part_1 = 0;
|
||||
long part_2 = 0;
|
||||
std::vector<int> part1_ints;
|
||||
std::vector<long> part2_longs;
|
||||
if (file.is_open()) {
|
||||
std::getline(file, line);
|
||||
while (!line.empty()) {
|
||||
part_1 = do_part_1(line);
|
||||
part1_ints.emplace_back(part_1);
|
||||
part_2 = do_part_2(line);
|
||||
part2_longs.emplace_back(part_2);
|
||||
std::getline(file, line);
|
||||
}
|
||||
} else {
|
||||
std::cerr << "Error opening file: " << path << std::endl;
|
||||
return {0, 0};
|
||||
}
|
||||
|
||||
part_1 = std::accumulate(part1_ints.begin(), part1_ints.end(), 0L);
|
||||
part_2 = std::accumulate(part2_longs.begin(), part2_longs.end(), 0L);
|
||||
|
||||
return {part_1, part_2};
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
if (argc < 2) {
|
||||
std::cout << "One argument required: input txt" << std::endl;
|
||||
}
|
||||
|
||||
auto results = parse_input_file(argv[1]);
|
||||
std::cout << "Part 1: " << std::get<0>(results) << std::endl;
|
||||
std::cout << "Part 2: " << std::get<1>(results) << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user