Find the winner of a game of removing any number of stones from the least indexed non | Function to find the winner of game between A and B ; win = 1 means B is winner win = 0 means A is winner ; If size is even , winner is B ; If size is odd , winner is A ; Stone will be removed by B ; B will take n - 1 stones from current pile having n stones and force A to pick 1 stone ; Stone will be removed by A ; A will take n - 1 stones from current pile having n stones and force B to pick 1 stone ; Print the winner accordingly ; Given piles of stone ; Function call
function findWinner ( a , n ) { let win = 0 ; if ( n % 2 == 0 ) win = 1 ; else win = 0 ; for ( let i = n - 2 ; i >= 0 ; i -- ) { if ( i % 2 == 1 ) { if ( win == 0 && a [ i ] > 1 ) win = 1 ; } else { if ( win == 1 && a [ i ] > 1 ) win = 0 ; } } if ( win == 0 ) document . write ( " " ) ; else document . write ( " " ) ; } let arr = [ 1 , 1 , 1 , 2 ] ; let N = arr . length ; findWinner ( arr , N ) ;