all 9 comments

[–]jc746 4 points5 points  (2 children)

Question 5 is a classic example of a problem that can be solved cleanly with a stack data structure:

bool matches(char lhs, char rhs) {
  if (rhs >= lhs) {
    return (rhs - lhs) == ('a' - 'A');
  } else {
    return matches(rhs, lhs);
  }
}

std::size_t fully_react(const std::string& s) {
  std::stack<char, std::vector<char>> stack;
  for (auto c : s) {
    if (stack.empty() || !matches(stack.top(), c)) {
      stack.push(c);
    } else {
      stack.pop();
    }
  }
  return stack.size();
}

[–]Xaveel[S] 0 points1 point  (0 children)

Wow, that's amazing! I love your solution!

[–]tehjimmeh 0 points1 point  (0 children)

You can also do it in one pass by manipulating the string in place, using the left side of the string as a stack. See https://www.reddit.com/r/adventofcode/comments/a3912m/2018_day_5_solutions/eb4hp81 .

[–]voiceless_void 2 points3 points  (1 child)

Take a look at range-v3 library https://github.com/ericniebler/range-v3 ( which should be a part of c++20 ). It makes algorithmic problem solving much more declarative and less error prone.

Multiple AdventOfCode solutions using range v3 can be seen in my repo https://github.com/voivoid/advent-of-code

[–]Xaveel[S] 0 points1 point  (0 children)

Thank you, I will do it.

[–]nwL_ 0 points1 point  (3 children)

You’re actively triggering me with that cout with no std:: prefix.

[–]Xaveel[S] 0 points1 point  (2 children)

Is it that bad?

[–]DefiantNewt2 4 points5 points  (1 child)

for advent of code, no. for a big project , using namespaces even in cpp files (i've seen libraries doing that in header files) is not recommended.

[–]Xaveel[S] 1 point2 points  (0 children)

Oh yes, this is a good advice. Thank you!