This commit is contained in:
Adam Jeniski 2025-12-13 22:22:02 -10:00
parent 6dbec069ca
commit 094dc367ad
2 changed files with 89 additions and 0 deletions

11
input/2025-5.sample.txt Normal file
View File

@ -0,0 +1,11 @@
3-5
10-14
16-20
12-18
1
5
8
11
17
32

78
src/day5.cpp Normal file
View File

@ -0,0 +1,78 @@
// :autocmd BufWritePost *.cpp :silent exec "!./build 5"
#include <algorithm>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
struct Range {
int64_t min;
int64_t max;
};
constexpr int compare(const Range &a, const Range &b) {
if (a.min == b.min) {
return a.max < b.max;
}
return a.min < b.min;
}
using Ranges = std::vector<Range>;
using Nums = std::vector<int64_t>;
int64_t part_1(const Ranges &ranges, const Nums &nums);
int64_t part_2(const Ranges &ranges, const Nums &nums);
int main() {
std::ifstream file{"input/2025-5.txt"};
std::string line;
Ranges ranges;
char throwaway;
while (std::getline(file, line) && line != "") {
Range r{};
sscanf(line.c_str(), "%ld-%ld", &r.min, &r.max);
ranges.push_back(r);
}
int64_t num;
Nums nums{};
while (file >> num) {
nums.push_back(num);
}
std::sort(ranges.begin(), ranges.end(), compare);
std::cout << "Part 1: " << part_1(ranges, nums) << std::endl;
std::cout << "Part 2: " << part_2(ranges, nums) << std::endl;
}
int64_t part_1(const Ranges &ranges, const Nums &nums) {
int64_t ans{};
for (auto num : nums) {
for (auto range : ranges) {
if (num >= range.min && num <= range.max) {
ans += 1;
break;
}
}
}
return ans;
}
int64_t part_2(const Ranges &ranges, const Nums &nums) {
int64_t ans{};
int64_t scanner{0};
for (auto range : ranges) {
if (scanner < range.min) {
auto temp{range.max - range.min + 1};
ans += temp;
scanner = range.max;
} else if (scanner <= range.max) {
auto temp{range.max - scanner};
ans += temp;
scanner = range.max;
}
}
return ans;
}