Pen Distribution Problem | C ++ implementation of the above approach ; Recursive function to play Game ; Box is empty , Game Over ! or Both have quit , Game Over ! ; P1 moves ; P2 moves ; Increment X ; Switch moves between P1 and P2 ; Function to find the number of pens remaining in the box and calculate score for each player ; Score of P1 ; Score of P2 ; Initialized to zero ; Move = 0 , P1 ' s ▁ turn ▁ ▁ Move ▁ = ▁ 1 , ▁ P2' s turn ; Has P1 quit ; Has P2 quit ; Recursively continue the game ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int & N , int & P1 , int & P2 , int & X , bool Move , bool QuitP1 , bool QuitP2 ) { if ( N == 0 or ( QuitP1 and QuitP2 ) ) { cout << " Number ▁ of ▁ pens ▁ remaining " << " ▁ in ▁ the ▁ box : ▁ " << N << endl ; cout << " Number ▁ of ▁ pens ▁ collected " << " ▁ by ▁ P1 : ▁ " << P1 << endl ; cout << " Number ▁ of ▁ pens ▁ collected " << " ▁ by ▁ P2 : ▁ " << P2 << endl ; return ; } if ( Move == 0 and QuitP1 == false ) { int req_P1 = pow ( 2 , X ) ; if ( req_P1 <= N ) { P1 += req_P1 ; N -= req_P1 ; } else { QuitP1 = true ; } } else if ( Move == 1 and QuitP2 == false ) { int req_P2 = pow ( 3 , X ) ; if ( req_P2 <= N ) { P2 += req_P2 ; N -= req_P2 ; } else { QuitP2 = true ; } } X ++ ; Move = ( ( Move == 1 ) ? 0 : 1 ) ; solve ( N , P1 , P2 , X , Move , QuitP1 , QuitP2 ) ; } void PenGame ( int N ) { int P1 = 0 ; int P2 = 0 ; int X = 0 ; bool Move = 0 ; bool QuitP1 = 0 ; bool QuitP2 = 0 ; solve ( N , P1 , P2 , X , Move , QuitP1 , QuitP2 ) ; } int main ( ) { int N = 22 ; PenGame ( N ) ; return 0 ; }