Pen Distribution Problem | Java 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
import java . util . * ; import java . lang . * ; public class GFG { static void solve ( int N , int P1 , int P2 , int X , int Move , boolean QuitP1 , boolean QuitP2 ) { if ( N == 0 || ( QuitP1 && QuitP2 ) ) { System . out . println ( " Number ▁ of ▁ pens ▁ remaining " + " ▁ in ▁ the ▁ box : ▁ " + N ) ; System . out . println ( " Number ▁ of ▁ pens ▁ collected " + " ▁ by ▁ P1 : ▁ " + P1 ) ; System . out . println ( " Number ▁ of ▁ pens ▁ collected " + " ▁ by ▁ P2 : ▁ " + P2 ) ; return ; } if ( Move == 0 && QuitP1 == false ) { int req_P1 = ( int ) ( Math . pow ( 2 , X ) ) ; if ( req_P1 <= N ) { P1 += req_P1 ; N -= req_P1 ; } else { QuitP1 = true ; } } else if ( Move == 1 && QuitP2 == false ) { int req_P2 = ( int ) ( 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 ) ; } static void PenGame ( int N ) { int P1 = 0 ; int P2 = 0 ; int X = 0 ; int Move = 0 ; boolean QuitP1 = false ; boolean QuitP2 = false ; solve ( N , P1 , P2 , X , Move , QuitP1 , QuitP2 ) ; } public static void main ( String [ ] args ) { int N = 22 ; PenGame ( N ) ; } }