Sort by

recency

|

1242 Discussions

|

  • + 0 comments

    This is my solution (python):

    !/bin/python3

    import math import os import random import re import sys import itertools

    #

    Complete the 'formingMagicSquare' function below.

    #

    The function is expected to return an INTEGER.

    The function accepts 2D_INTEGER_ARRAY s as parameter.

    #

    def formingMagicSquare(arr): all_val = [] for row in arr: for col in row: all_val.append(col)

    const = list(range(1, 10))
    all_comb_r = list(itertools.permutations(const, 9))
    
    all_valid_comb = []
    
    for comb in all_comb_r:
        c = list(comb)
        temp = []
        curr = []
        curr_col = []
        curr_d = []
        for val in c:
            temp.append(val)
            if len(temp) == 3:
                curr.append(temp)
                temp = []
    
        temp = []
        for i in range(len(curr)):
            for j in range(len(curr[i])):
                temp.append(curr[j][i])
                if len(temp) == 3:
                    curr_col.append(temp)
                    temp = []
        temp = []
        for i in range(len(curr)):
            temp.append(curr[i][i])
            if len(temp) == 3:
                curr_d.append(temp)
                temp = []
    
        s = 0
        e = 2
        for i in range(len(curr)):
            temp.append(curr[s][e])
            if len(temp) == 3:
                curr_d.append(temp)
                temp = []
            s += 1
            e -= 1
    
        sum_curr = [sum(i) for i in curr]
        sum_curr_col = [sum(i) for i in curr_col]
        sum_curr_d = [sum(i) for i in curr_d]
    
        all_val = []
        for num in range(3):
            all_val.append(sum_curr[num])
            all_val.append(sum_curr_col[num])
            if num != 2:
                all_val.append(sum_curr_d[num])
    
        if all(i == all_val[0] for i in all_val):
            all_valid_comb.append(curr)
    
    all_ans = []
    for i in range(len(all_valid_comb)):
        curr_ans = 0
        for j in range(len(all_valid_comb[i])):
            for a in range(len(all_valid_comb[i][j])):
                if all_valid_comb[i][j][a] != arr[j][a]:
                    curr_ans += abs(all_valid_comb[i][j][a] - arr[j][a])
        all_ans.append(curr_ans)
    
    return min(all_ans)
    

    if name == 'main': fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = []
    
    for _ in range(3):
        s.append(list(map(int, input().rstrip().split())))
    
    result = formingMagicSquare(s)
    
    fptr.write(str(result) + '\n')
    
    fptr.close()
    
  • + 0 comments

    I do like this. 1st. Unroll the input matrix to long list. (imagine the list 9 items was rolled in clockwise direction to create a 3x3 matrix),

    2nd. Create the unrolled List of the Magic Square , since magic square can rotate or flip, so the List has some repeat pattern, and I have to create another reverse List.

    ``List<int> rightRotateList 
            = new List<int>{8,3,4,9,2,7,6,1,8,3,4,9,2,7,6};
        List<int> leftRotateList
            = new List<int>(rightRotateList);
        leftRotateList.Reverse();
    

    Notice I have exclude the center number of magic square, number 5, since it's unchanged in every version of magic square 3x3.

    3rd. Calculate the cost and compare. Here is the full code in C#

       ````
     public static int formingMagicSquare(List<List<int>> s)
    
    {
        List<int> costList = new List<int>();
    
        List<int> sToList = s[0];
        sToList.Add(s[1][2]);
        sToList.Add(s[2][2]);
        sToList.Add(s[2][1]);
        sToList.Add(s[2][0]);
        sToList.Add(s[1][0]);
    
        List<int> rightRotateList 
            = new List<int>{8,3,4,9,2,7,6,1,8,3,4,9,2,7,6};
        List<int> leftRotateList
            = new List<int>(rightRotateList);
        leftRotateList.Reverse();
    
        for (int i = 0 ; i < 4 ; i++)
        {
            var costRight = 0 ;
            var costLeft = 0 ;
            for (int j = 0 ; j < sToList.Count ; j++)
            {
                costRight += Math.Abs(sToList[j] - rightRotateList[i*2 + j]);
                costLeft += Math.Abs(sToList[j] - leftRotateList[i*2 + j]);
            }
            var centerMatrixDiff = Math.Abs(s[1][1] - 5);
            costList.Add(costRight + centerMatrixDiff);
            costList.Add(costLeft + centerMatrixDiff);
    
        }
    
        return costList.Min();
        // return costList;
    
    }
    

    ` 4th. It's easier to explain in image, but I don't know how to upload here. So I uploaded to this image hosting service https://ibb.co/sjwBpwZ

  • + 0 comments
    function formingMagicSquare(s) {
        
        var M = 15
        var y = 5
        var x = 3
        var j = [... new Array(3)].map(x =>Array(3).fill())
        
        var flat_s = s.flat()
        
            const magicSquares = [
            [8, 1, 6, 3, 5, 7, 4, 9, 2],
            [6, 1, 8, 7, 5, 3, 2, 9, 4],
            [4, 9, 2, 3, 5, 7, 8, 1, 6],
            [2, 9, 4, 7, 5, 3, 6, 1, 8],
            [8, 3, 4, 1, 5, 9, 6, 7, 2],
            [4, 3, 8, 9, 5, 1, 2, 7, 6],
            [6, 7, 2, 1, 5, 9, 8, 3, 4],
            [2, 7, 6, 9, 5, 1, 4, 3, 8]
        ];
        
        var flat_squres = magicSquares.flat()
        
    
        
    var sum = Infinity
    var current_sum = 0
     
     var j = 0   
     for(var i = 0; i < flat_squres.length;i++){
        
        console.log(`m ${flat_squres[i]} vs ${flat_s[j]}`)
        current_sum += Math.abs(flat_squres[i] - flat_s[j])
        j = j + 1
        if (j == 9){
            
    
            sum = sum > current_sum ? current_sum : sum
            current_sum = 0
            j = 0
            
        }
    
     }
     
     console.log(sum)
     return sum
    
        
        
        
    }
    
  • + 0 comments

    JS/Javascript solution:-

    function formingMagicSquare(s) {
        // Flatten the input 2D array
        const flatInput = s.flat();
    
        // Define all possible 3x3 magic squares
        const magicSquares = [
            [8, 1, 6, 3, 5, 7, 4, 9, 2],
            [6, 1, 8, 7, 5, 3, 2, 9, 4],
            [4, 9, 2, 3, 5, 7, 8, 1, 6],
            [2, 9, 4, 7, 5, 3, 6, 1, 8],
            [8, 3, 4, 1, 5, 9, 6, 7, 2],
            [4, 3, 8, 9, 5, 1, 2, 7, 6],
            [6, 7, 2, 1, 5, 9, 8, 3, 4],
            [2, 7, 6, 9, 5, 1, 4, 3, 8]
        ];
    
        // Calculate the minimum cost to convert to any magic square
        let minCost = Infinity;
    
        for (const magic of magicSquares) {
            let cost = 0;
            for (let i = 0; i < 9; i++) {
                cost += Math.abs(flatInput[i] - magic[i]);
            }
            minCost = Math.min(minCost, cost);
        }
    
        return minCost;
    }
    
  • + 0 comments
    def formingMagicSquare(s):
        magic_matrix = [
            [[8, 1, 6], [3, 5, 7], [4, 9, 2]],
            [[6, 1, 8], [7, 5, 3], [2, 9, 4]],
            [[4, 9, 2], [3, 5, 7], [8, 1, 6]],
            [[2, 9, 4], [7, 5, 3], [6, 1, 8]],
            [[8, 3, 4], [1, 5, 9], [6, 7, 2]],
            [[4, 3, 8], [9, 5, 1], [2, 7, 6]],
            [[6, 7, 2], [1, 5, 9], [8, 3, 4]],
            [[2, 7, 6], [9, 5, 1], [4, 3, 8]]
        ]
        costs = []
        for matrix in magic_matrix:
            diff = []
            for i in range(3):
                for j in range(3):
                    diff.append(abs(s[i][j] - matrix[i][j]))
            costs.append(sum(diff))
        
        return min(costs)