master
Benjamin Kraft 2 years ago
parent d58841276b
commit b0b506d60c
  1. 53
      src/days/04/Day04.cpp
  2. 8
      src/days/04/Day04.h
  3. 2
      src/util.h

@ -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;
}

@ -2,9 +2,17 @@
#include "../../Day.h"
typedef pair<int, int> Range;
typedef pair<Range, Range> RangePair;
class Day04 : public Day {
protected:
Result Task1() override;
Result Task2() override;
vector<RangePair> parse() const;
static bool contains(Range, Range);
static bool overlap(Range, Range);
};

@ -9,4 +9,4 @@
using std::stoi, std::to_string;
using std::cout, std::endl;
using std::string, std::vector, std::set;
using std::string, std::vector, std::set, std::pair;
Loading…
Cancel
Save