Permutation game Discussions | Algorithms | HackerRank
  • + 0 comments

    Combination of previous answers, C++.

    class PermutationGame
    {
    private:
        unordered_set<string> _winningNumbers;
    
        bool isIncreasing(string str)
        {
            if (str.size() == 1) return 1;        
            auto it = str.begin();
            int prev = *it++;
            for (; it != str.end(); it++)
            {
                if (*it <= prev) return false;
                prev = *it;
            }
            return true;
        }
    
        string encode(vector<int> arr)
        {
            string s;
            for (auto number : arr)
                s.push_back(number < 10 ? (number + '0') : 
                                          (number - 10 + 'A'));
            return s;
        }
    
        bool checkCurrentPlayerWins(string numbers)
        {
            // With this sequence, the current player has already won 
            // => player wins
            if (_winningNumbers.find(numbers) !=_winningNumbers.end())
                return true;
    
            // Sequence increases after opponent's turn =>
    				// current player loses
            if (isIncreasing(numbers))
                return false;
    
            for (int i = 0, len = (int)numbers.size(); i < len; i++)
            {
                char erased = numbers[i];
                // Making a move
                numbers.erase(i, 1);     
                
                // Checking if the opponent wins
                bool opponentWins = checkCurrentPlayerWins(numbers);
                
                // Reverse the move
                numbers.insert(i, 1, erased);
    
                // If the opponent loses, then the current player wins
                if (!opponentWins)
                {
                    // Keeping the Winning Sequence
                    _winningNumbers.insert(numbers);                      
                    return true;
                }           
            }
            // None of the moves resulted in the player's victory => 
            // player loses
            return false;
        }
    
    public:
        bool checkCurrentPlayerWins(vector<int> arr)
        {                
            bool result = checkCurrentPlayerWins(encode(arr));
            _winningNumbers.clear();
            return result;
        }
    };
    
    string permutationGame(vector<int> arr) 
    {
        PermutationGame pg;
        return pg.checkCurrentPlayerWins(arr) ? "Alice" : "Bob";
    }