From 3c8331701f9f77c28847d678b935d5efb9a5d575 Mon Sep 17 00:00:00 2001 From: Sebastiano Tronto Date: Thu, 19 Dec 2024 07:21:47 +0100 Subject: Improved part 2 day 19 2024 with string_view --- 2024/19/day19b.cpp | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) (limited to '2024/19/day19b.cpp') diff --git a/2024/19/day19b.cpp b/2024/19/day19b.cpp index 6f8b8f4..dd6055d 100644 --- a/2024/19/day19b.cpp +++ b/2024/19/day19b.cpp @@ -11,28 +11,27 @@ #include using namespace std; -vector gettowels(const string& line) { - vector ret; - int j = 0; - for (int i = 0; j != -1; i = j+2) { +vector gettowels(const string_view& line) { + vector ret; + unsigned sz = line.size(); + for (int i = 0, j = 0; j != -1; i = j+2) { j = line.find(",", i); - ret.push_back(line.substr(i, (j == -1 ? line.size() : j)-i)); + ret.push_back(line.substr(i, (j == -1 ? sz : j) - i)); } return ret; } -int64_t countpossible(const string& p, const vector& towels, vector& mem) { - if (p.size() == 0) - return 1; - if (mem[p.size()] != -1) - return mem[p.size()]; +int64_t f(const string_view& p, const vector& towels, vector& mem) { + unsigned lp = p.size(); + if (lp == 0) return 1; + if (mem[lp] != -1) return mem[lp]; int64_t ret = 0; for (auto t : towels) { - if (t == p.substr(0, t.size())) - ret += countpossible(p.substr( - t.size(), p.size() - t.size()), towels, mem); + unsigned lt = t.size(); + if (t == p.substr(0, lt)) + ret += f(p.substr(lt, lp - lt), towels, mem); } - return (mem[p.size()] = ret); + return (mem[lp] = ret); } int main() { @@ -47,7 +46,7 @@ int main() { int64_t count = 0; for (auto p : patterns) { for (auto& m : mem) m = -1; - count += countpossible(p, towels, mem); + count += f(p, towels, mem); } cout << count << endl; return 0; -- cgit v1.3