Tower Breakers Hacker Rank Solution Best & Easiest

Tower Breakers Problem Solution
Tower Breakers Problem Solution

In this post, we will solve the Tower Breakers Jumps HackerRank Solution. This problem (Tower Breakers) is a part of the HackerRank Problem Solving series.

Two players are playing a game of Tower Breakers! Player 1 always moves first, and both players always play optimally.The rules of the game are as follows:

  • Initially there are n towers.
  • Each tower is of height m.
  • The players move in alternating turns.
  • In each turn, a player can choose a tower of height x and reduce its height to y, where  and  evenly divides .
  • If the current player is unable to make a move, they lose the game.

Given the values of  and , determine which player will win. If the first player wins, return . Otherwise, return.

Tower Breakers Hacker Rank Solution

Problem solution in Python programming:

def towerBreakers(n, m):
    #return 1 + (not n&1 or m==1)
    
    def ceil(n):
        return int(n) + boolify(n % 1) 
        
    def boolify(n):
        try:
            n //= n
            return n
        except:
            return 0
    
    return 1 + ceil( ( ( (n & 1) - 1) * -1 + ( boolify( m - 1 ) - 1 ) * -1 ) / 2 )

Problem solution in JavaScript programming:

function towerBreakers(n, m) {
    if(m==1){
        return 2;
    }
    if(n%2==0){
        return 2;
    }else{
        return 1;
    }
}

Problem solution in Java programming:

public static int towerBreakers(int n, int m) {
        boolean evenTowers = n%2==0;
        boolean gotMoves = m>1;
        
        if(!gotMoves){
            return 2;
        }
        
        if(evenTowers){
            return 2;
        }
        
        return 1;
    }