Permutation game Discussions | Algorithms | HackerRank
We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
classPermutationGame{private:unordered_set<string>_winningNumbers;boolisIncreasing(stringstr){if(str.size()==1)return1;autoit=str.begin();intprev=*it++;for(;it!=str.end();it++){if(*it<=prev)returnfalse;prev=*it;}returntrue;}stringencode(vector<int>arr){strings;for(autonumber:arr)s.push_back(number<10?(number+'0'):(number-10+'A'));returns;}boolcheckCurrentPlayerWins(stringnumbers){// With this sequence, the current player has already won // => player winsif(_winningNumbers.find(numbers)!=_winningNumbers.end())returntrue;// Sequence increases after opponent's turn =>// current player losesif(isIncreasing(numbers))returnfalse;for(inti=0,len=(int)numbers.size();i<len;i++){charerased=numbers[i];// Making a movenumbers.erase(i,1);// Checking if the opponent winsboolopponentWins=checkCurrentPlayerWins(numbers);// Reverse the movenumbers.insert(i,1,erased);// If the opponent loses, then the current player winsif(!opponentWins){// Keeping the Winning Sequence_winningNumbers.insert(numbers);returntrue;}}// None of the moves resulted in the player's victory => // player losesreturnfalse;}public:boolcheckCurrentPlayerWins(vector<int>arr){boolresult=checkCurrentPlayerWins(encode(arr));_winningNumbers.clear();returnresult;}};stringpermutationGame(vector<int>arr){PermutationGamepg;returnpg.checkCurrentPlayerWins(arr)?"Alice":"Bob";}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Permutation game
You are viewing a single comment's thread. Return to all comments →
Combination of previous answers, C++.