From 8ed21d95505606281a7954df3e62070c90448bb5 Mon Sep 17 00:00:00 2001 From: Nick Krichevsky Date: Sat, 5 Dec 2020 01:19:46 -0500 Subject: [PATCH] Refactor findMissingNumber to use templates --- day5/day5.cpp | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/day5/day5.cpp b/day5/day5.cpp index 100a5d6..c5530be 100644 --- a/day5/day5.cpp +++ b/day5/day5.cpp @@ -69,6 +69,21 @@ int parseSeatID(std::string_view view) { return rowId * (MAX_COL + 1) + colId; } +template +typename std::iterator_traits::value_type findMissingNumber(Iter begin, Iter end) { + auto lastNumber = *begin; + for (Iter it = std::next(begin); it != end; it++) { + if (*it != lastNumber + 1) { + return lastNumber + 1; + } + + lastNumber = *it; + } + + throw std::invalid_argument("No missing number in iterator"); +} + + int part1(const std::vector &input) { return std::accumulate(input.cbegin(), input.cend(), 0, [](int max, const std::string &row) { int seatId = parseSeatID(row); @@ -83,15 +98,7 @@ int part2(const std::vector &input) { }); std::sort(ids.begin(), ids.end()); - int lastId = ids.at(0); - for (auto it = std::next(ids.begin()); it != ids.end(); it++) { - if (*it != lastId + 1) { - return lastId + 1; - } - lastId = *it; - } - - throw std::invalid_argument("No solution in given input"); + return findMissingNumber(ids.begin(), ids.end()); } int main(int argc, char *argv[]) {