aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--2024/src/day02.cpp35
1 files changed, 17 insertions, 18 deletions
diff --git a/2024/src/day02.cpp b/2024/src/day02.cpp
index c8ca66f..e3597a3 100644
--- a/2024/src/day02.cpp
+++ b/2024/src/day02.cpp
@@ -1,4 +1,3 @@
1#include <cstddef>
2#include <fstream> 1#include <fstream>
3#include <iostream> 2#include <iostream>
4#include <sstream> 3#include <sstream>
@@ -12,11 +11,11 @@ read_file(string_view filename)
12 fstream input{ filename }; 11 fstream input{ filename };
13 vector<vector<long>> lines; 12 vector<vector<long>> lines;
14 13
15 auto split = [](const string& str) { 14 auto split = [](const string& line) {
16 stringstream sstr{ str }; 15 stringstream line_stream{ line };
17 vector<long> values; 16 vector<long> values;
18 17
19 for ( long value = 0; sstr >> value; ) { 18 for ( long value = 0; line_stream >> value; ) {
20 values.emplace_back(value); 19 values.emplace_back(value);
21 } 20 }
22 return values; 21 return values;
@@ -25,7 +24,6 @@ read_file(string_view filename)
25 for ( string line; getline(input, line); ) { 24 for ( string line; getline(input, line); ) {
26 lines.emplace_back(split(line)); 25 lines.emplace_back(split(line));
27 } 26 }
28
29 return lines; 27 return lines;
30} 28}
31 29
@@ -43,6 +41,19 @@ is_safe(const vector<long>& values)
43 return all_positive || all_negative; 41 return all_positive || all_negative;
44} 42}
45 43
44bool
45is_real_safe(const vector<long>& values)
46{
47 for ( size_t i = 0; i != values.size(); ++i ) {
48 auto values_copy = values;
49 values_copy.erase(values_copy.begin() + ptrdiff_t(i));
50 if ( is_safe(values_copy) ) {
51 return true;
52 }
53 }
54 return false;
55}
56
46void 57void
47part1(const vector<vector<long>>& lines) 58part1(const vector<vector<long>>& lines)
48{ 59{
@@ -52,19 +63,7 @@ part1(const vector<vector<long>>& lines)
52void 63void
53part2(const vector<vector<long>>& lines) 64part2(const vector<vector<long>>& lines)
54{ 65{
55 long safe_count = 0; 66 cout << ranges::count_if(lines, is_real_safe) << endl;
56 for ( const auto& line: lines ) {
57 auto safe = false;
58 for ( size_t i = 0; i != line.size(); ++i ) {
59 auto copy = line;
60 copy.erase(copy.begin() + ptrdiff_t(i));
61 safe |= is_safe(copy);
62 }
63 if ( safe ) {
64 ++safe_count;
65 }
66 }
67 cout << safe_count << endl;
68} 67}
69 68
70int 69int