293 Flip Game

You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take turns to flip twoconsecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner. Write a function to compute all possible states of the string after one valid move. For example, given s = "++++", after one move, it may become one of the following states:

    [
      "--++",
      "+--+",
      "++--"
    ]

If there is no valid move, return an empty list [].

  #include <iostream>
  #include <string>
  #include <vector>
  using namespace std;

  vector<string> nextPossibleMoves(string s)
  {
      int memory = 0;
      string goBack = s;
      vector<string> moves;
      while (memory < s.size() - 1)
      {
          for (int i = memory; i < s.size(); i++)
          {
              if (i == s.size() - 1) break;
              if (s.at(i) == '+' && s.at(i + 1) == '+')
              {
                  // replace(position, length, string)
                  s = s.replace(i, 2, "--");
                  moves.push_back(s);
                  s = goBack;
                  memory = i + 1;
                  break;
              }
              else memory += 2;
          }
      }
      return moves;

  }

  int main()
  {
      vector<string> moves = nextPossibleMoves("--++--++-----------++++++++++++---++---+++++++---++-+");

      for (auto i : moves) cout << i << endl;
  }

Last updated