Forming a Magic Square

  • + 0 comments

    Idk why all the python answers assume you'd have access to a list of all magic squares when doing this problem.I guess to game the hackerrank rankings? Not very helpful for people actually trying to learn. Anyways, Here's how I would solve this on an actual test, including code to find all magic squares:

    def is_magic(s):
        
        # Rows
        if not all(sum(row) == 15 for row in s):
            return False
    
        # Columns
        for col in range(3):
            if s[0][col] + s[1][col] + s[2][col] != 15:
                return False
    
        # Diagonals
        if (s[0][0] + s[1][1] + s[2][2] != 15 or
            s[0][2] + s[1][1] + s[2][0] != 15):
            return False
    
        return True
        
        
    def formingMagicSquare(s):
        magic_squares = []
        
        for perm in permutations(range(1, 10)): 
            
            square = [list(perm[0:3]), list(perm[3:6]), list(perm[6:9])]
            
            if is_magic(square):
                magic_squares.append(square)
    
    
        min_cost = math.inf
        for square in magic_squares:
            cost = 0
            for i in range(3):
                for j in range(3):
                    cost+=abs(s[i][j] - square[i][j])
            
            min_cost = min(min_cost,cost)
        
        return min_cost