summaryrefslogtreecommitdiff
path: root/2023/05/src/part1.cpp
diff options
context:
space:
mode:
Diffstat (limited to '2023/05/src/part1.cpp')
-rw-r--r--2023/05/src/part1.cpp84
1 files changed, 84 insertions, 0 deletions
diff --git a/2023/05/src/part1.cpp b/2023/05/src/part1.cpp
new file mode 100644
index 0000000..d58c0cb
--- /dev/null
+++ b/2023/05/src/part1.cpp
@@ -0,0 +1,84 @@
1#include <iostream>
2#include <fstream>
3#include <sstream>
4#include <tuple>
5#include <vector>
6
7#include "util.h"
8
9using Seeds = std::vector<long>;
10using Step = std::vector<std::tuple<long,long,long>>;
11using Almanac = std::vector<Step>;
12
13constexpr char SEEDS[] = "seeds:";
14
15std::pair<Seeds,Almanac> parse_input()
16{
17 Seeds seeds;
18 Almanac almanac;
19
20 std::ifstream input{ "resources/input.txt" };
21 if (input.is_open())
22 {
23 std::string line;
24
25 /* Seeds */
26 long seed;
27 std::getline(input,line);
28 std::istringstream sline{ line };
29 sline >> util::skip<SEEDS>;
30 while (sline >> seed)
31 {
32 seeds.push_back(seed);
33 }
34
35 /* Mappings */
36 Step step;
37 long from, to, size;
38 while (not std::getline(input,line).eof())
39 {
40 if (line.empty()) continue;
41
42 if (std::isdigit(line[0]))
43 {
44 std::istringstream sline{ line };
45 sline >> to >> from >> size;
46 step.push_back(std::make_tuple(from, from + size, to - from));
47 }
48 else if (not step.empty())
49 {
50 almanac.push_back(std::move(step));
51 step = {};
52 }
53 }
54 almanac.push_back(std::move(step));
55 }
56 input.close();
57
58 return std::make_pair(std::move(seeds), std::move(almanac));
59}
60
61int main(void)
62{
63 Seeds seeds;
64 Almanac almanac;
65 std::tie(seeds, almanac) = parse_input();
66
67 for (const auto& step : almanac)
68 {
69 for (auto& seed : seeds)
70 {
71 for (const auto& map : step)
72 {
73 if (std::get<0>(map) <= seed and seed < std::get<1>(map))
74 {
75 seed += std::get<2>(map);
76 break; // mappings in a step don't overlap
77 }
78 }
79 }
80 }
81
82 std::cout << *std::min_element(seeds.begin(), seeds.end()) << std::endl;
83 return 0;
84}