parent
d58841276b
commit
b0b506d60c
3 changed files with 61 additions and 4 deletions
@ -1,9 +1,58 @@ |
||||
#include "Day04.h" |
||||
|
||||
Result Day04::Task1() { |
||||
return Day::Task1(); |
||||
int count = 0; |
||||
for (const RangePair &pair : parse()){ |
||||
const Range range1 = pair.first; |
||||
const Range range2 = pair.second; |
||||
|
||||
if (contains(range1, range2) || contains(range2, range1)) |
||||
count++; |
||||
} |
||||
|
||||
return to_string(count); |
||||
} |
||||
|
||||
Result Day04::Task2() { |
||||
return Day::Task2(); |
||||
int count = 0; |
||||
for (const RangePair &pair : parse()){ |
||||
const Range range1 = pair.first; |
||||
const Range range2 = pair.second; |
||||
|
||||
if (overlap(range1, range2)) |
||||
count++; |
||||
} |
||||
|
||||
return to_string(count); |
||||
} |
||||
|
||||
bool Day04::contains(Range outer, Range inner) { |
||||
return outer.first <= inner.first && outer.second >= inner.second; |
||||
} |
||||
|
||||
bool Day04::overlap(Range r1, Range r2) { |
||||
bool R1LeftFromR2 = r1.first < r2.first && r1.second < r2.first; |
||||
bool R2LeftFromR1 = r2.first < r1.first && r2.second < r1.first; |
||||
return !(R1LeftFromR2 || R2LeftFromR1); |
||||
} |
||||
|
||||
vector<RangePair> Day04::parse() const { |
||||
vector<RangePair> parsed; |
||||
for (const string &line : input){ |
||||
const size_t comma = line.find(','); |
||||
const string range1 = line.substr(0, comma); |
||||
const string range2 = line.substr(comma + 1); |
||||
|
||||
const size_t dash1 = range1.find('-'); |
||||
const size_t dash2 = range2.find('-'); |
||||
|
||||
const int p1n1 = stoi(range1.substr(0, dash1)); |
||||
const int p1n2 = stoi(range1.substr(dash1 + 1)); |
||||
|
||||
const int p2n1 = stoi(range2.substr(0, dash2)); |
||||
const int p2n2 = stoi(range2.substr(dash2 + 1)); |
||||
|
||||
parsed.emplace_back(Range(p1n1, p1n2), Range(p2n1, p2n2)); |
||||
} |
||||
return parsed; |
||||
} |
Loading…
Reference in new issue