mirror of
https://github.com/szymon-jozef/advent_of_code_2025.git
synced 2026-06-05 17:00:09 +02:00
day 5, challange 2
This commit is contained in:
11
5th_day/2/example.txt
Normal file
11
5th_day/2/example.txt
Normal file
@@ -0,0 +1,11 @@
|
||||
3-5
|
||||
10-14
|
||||
16-20
|
||||
12-18
|
||||
|
||||
1
|
||||
5
|
||||
8
|
||||
11
|
||||
17
|
||||
32
|
||||
1168
5th_day/2/input.txt
Normal file
1168
5th_day/2/input.txt
Normal file
File diff suppressed because it is too large
Load Diff
75
5th_day/2/main.cpp
Normal file
75
5th_day/2/main.cpp
Normal file
@@ -0,0 +1,75 @@
|
||||
#include <algorithm>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
struct Range {
|
||||
long long begining;
|
||||
long long end;
|
||||
};
|
||||
|
||||
vector<string> read_file(const string &FILE_NAME) {
|
||||
ifstream file(FILE_NAME);
|
||||
string s;
|
||||
|
||||
vector<string> result;
|
||||
|
||||
while (getline(file, s)) {
|
||||
result.push_back(s);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
vector<Range> get_fresh_ids(const vector<string> input) {
|
||||
vector<Range> fresh_ids;
|
||||
for (string line : input) {
|
||||
if (line.empty()) {
|
||||
break;
|
||||
}
|
||||
string begining, end;
|
||||
begining = line.substr(0, line.find("-"));
|
||||
end = line.substr(line.find("-") + 1);
|
||||
Range l_range = {stoll(begining), stoll(end)};
|
||||
fresh_ids.push_back(l_range);
|
||||
}
|
||||
|
||||
return fresh_ids;
|
||||
}
|
||||
|
||||
bool compareRanges(const Range &a, const Range &b) {
|
||||
return a.begining < b.begining;
|
||||
}
|
||||
|
||||
int main() {
|
||||
const string FILE_NAME = "input.txt";
|
||||
|
||||
vector<string> input = read_file(FILE_NAME);
|
||||
vector<Range> fresh_ids = get_fresh_ids(input);
|
||||
long long count = 0;
|
||||
|
||||
sort(fresh_ids.begin(), fresh_ids.end(), compareRanges);
|
||||
|
||||
vector<Range> merged_fresh_ids;
|
||||
merged_fresh_ids.push_back(fresh_ids[0]);
|
||||
|
||||
for (int i = 1; i < fresh_ids.size(); i++) {
|
||||
Range current_range = fresh_ids[i];
|
||||
Range &last_range = merged_fresh_ids.back();
|
||||
|
||||
if (current_range.begining <= last_range.end + 1) {
|
||||
last_range.end = max(last_range.end, current_range.end);
|
||||
} else {
|
||||
merged_fresh_ids.push_back(current_range);
|
||||
}
|
||||
}
|
||||
|
||||
for (Range range : merged_fresh_ids) {
|
||||
count += range.end - range.begining + 1;
|
||||
}
|
||||
|
||||
cout << count;
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user