Day2Part1
This commit is contained in:
parent
86dcbd3aaf
commit
5d1d878d78
7 changed files with 117 additions and 18 deletions
83
day2/main.cpp
Normal file
83
day2/main.cpp
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <expected>
|
||||
#include <print>
|
||||
#include <ranges>
|
||||
|
||||
struct IDRange {
|
||||
std::string leftRange;
|
||||
std::string rightRange;
|
||||
};
|
||||
|
||||
auto parseRanges(const std::string& filename) -> std::expected<std::vector<IDRange>, std::string> {
|
||||
std::ifstream inputF {filename};
|
||||
|
||||
if (!inputF){
|
||||
return std::unexpected{"Some file open error.\n"};
|
||||
}
|
||||
std::vector<IDRange> idRanges{};
|
||||
|
||||
std::string bigString{};
|
||||
std::getline(inputF,bigString);
|
||||
auto ranges = std::ranges::to<std::vector<std::string>>(std::views::split(bigString, ','));
|
||||
|
||||
for(const auto& range : ranges){
|
||||
auto subParts = std::ranges::to<std::vector<std::string>>(std::views::split(range, '-'));
|
||||
idRanges.emplace_back(subParts[0], subParts[1]);
|
||||
}
|
||||
|
||||
inputF.close();
|
||||
|
||||
return std::move(idRanges);
|
||||
}
|
||||
|
||||
|
||||
|
||||
auto countDoubles(const std::vector<IDRange>& idRanges) {
|
||||
long doubles{};
|
||||
for(const auto& rng : idRanges){
|
||||
//std::println("{}-{}", rng.leftRange, rng.rightRange);
|
||||
for( long i = std::stol(rng.leftRange); i <= std::stol(rng.rightRange); i++){
|
||||
auto str_version = std::to_string(i) ;
|
||||
auto str_len = str_version.size();
|
||||
//std::print("Checking {}. Length: {}", str_version, str_version.size());
|
||||
if (str_len % 2 == 0) {
|
||||
//std::print(" Divisible by two, splitting...");
|
||||
std::string_view left_half = std::string_view(str_version).substr(0, str_len/2);
|
||||
std::string_view right_half = std::string_view(str_version).substr(str_len/2, str_len);
|
||||
//std::print("Halves: {}/{}",left_half, right_half);
|
||||
if(left_half == right_half){
|
||||
//std::print(" EQUAL!");
|
||||
doubles += i;
|
||||
}
|
||||
}
|
||||
//std::println();
|
||||
}
|
||||
}
|
||||
return doubles;
|
||||
}
|
||||
|
||||
auto main() -> int {
|
||||
auto testCase = parseRanges("test_input");
|
||||
if(testCase) {
|
||||
auto testResult = countDoubles(*testCase);
|
||||
std::println("Testcase result: {}", testResult);
|
||||
}
|
||||
else{
|
||||
std::print("{}\n", testCase.error());
|
||||
}
|
||||
|
||||
|
||||
auto realRanges = parseRanges("puzzle_input");
|
||||
if(realRanges) {
|
||||
auto realResult = countDoubles(*realRanges);
|
||||
std::println("Real result: {}", realResult);
|
||||
}
|
||||
else{
|
||||
std::print("{}\n", realRanges.error());
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue