Pen Distribution Problem | 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
function solve ( N , P1 , P2 , X , Move , QuitP1 , QuitP2 ) { if ( N == 0 || ( QuitP1 && QuitP2 ) ) { document . write ( " " + " " + N + " " ) ; document . write ( " " + " " + P1 + " " ) ; document . write ( " " + " " + P2 + " " ) ; return ; } if ( Move == 0 && QuitP1 == false ) { let req_P1 = ( Math . pow ( 2 , X ) ) ; if ( req_P1 <= N ) { P1 += req_P1 ; N -= req_P1 ; } else { QuitP1 = true ; } } else if ( Move == 1 && QuitP2 == false ) { let req_P2 = ( Math . 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 ) ; } function PenGame ( N ) { let P1 = 0 ; let P2 = 0 ; let X = 0 ; let Move = 0 ; let QuitP1 = false ; let QuitP2 = false ; solve ( N , P1 , P2 , X , Move , QuitP1 , QuitP2 ) ; } let N = 22 ; PenGame ( N ) ;