Tower breakers hackerrank solution js
Here is a solution to the "Tower Breakers" problem on HackerRank in JavaScript:
function towerBreakers(n, m) {
if (n % 2 === 0) {
return m % 2 === 0? 2 : 1;
} else {
return m % 2 === 0? 1 : 2;
}
}
Here's an explanation of the solution:
The problem states that Alice and Bob are playing a game where they take turns breaking towers. The goal is to break all the towers. The game starts with n
towers, and each player can break at most m
towers in their turn.
The problem can be solved by analyzing the parity of n
and m
. If n
is even, then Alice will always win because she can break m
towers in her first turn, leaving n - m
towers for Bob, which is also even. If m
is even, then Bob will win because he can break m
towers in his first turn, leaving n - m
towers for Alice, which is also even.
If n
is odd, then the game is more complex, but we can still determine the winner by analyzing the parity of m
. If m
is even, then Alice will win because she can break m
towers in her first turn, leaving n - m
towers for Bob, which is odd. If m
is odd, then Bob will win because he can break m
towers in his first turn, leaving n - m
towers for Alice, which is even.
The solution uses a simple if-else statement to determine the winner based on the parity of n
and m
. If n
is even, the function returns 2
if m
is even, and 1
if m
is odd. If n
is odd, the function returns 1
if m
is even, and 2
if m
is odd.
You can test this function with different inputs to see that it correctly determines the winner of the game.