• + 0 comments

    My JavaScript Solution

    function formingMagicSquare(s) {
        // Write your code here
        
    const square1 =  [[8, 1, 6], [3, 5, 7], [4, 9, 2]];
    
    const square2 =  [[6, 1, 8], [7, 5, 3], [2, 9, 4]];
    
    const square3 =  [[4, 9, 2], [3, 5, 7], [8, 1, 6]];
    
    const square4 =  [[2, 9, 4], [7, 5, 3], [6, 1, 8]];
    
    const square5 =  [[8, 3, 4], [1, 5, 9], [6, 7, 2]];
    
    const square6 =  [[4, 3, 8], [9, 5, 1], [2, 7, 6]];
    
    const square7 =  [[6, 7, 2], [1, 5, 9], [8, 3, 4]];
    
    const square8 =  [[2, 7, 6], [9, 5, 1], [4, 3, 8]];
    
    
    function calculateDifference(s,t) {
        
    const diff = 
        
     Math.abs ( s[0][0] - t[0][0] ) + Math.abs ( s[0][1] - t[0][1] ) + Math.abs ( s[0][2] - t[0][2] ) + 
     
     Math.abs ( s[1][0] - t[1][0] ) + Math.abs ( s[1][1] - t[1][1] )  + Math.abs ( s[1][2] - t[1][2] ) +  
     
     Math.abs ( s[2][0] - t[2][0] ) + Math.abs ( s[2][1] - t[2][1] )  + Math.abs ( s[2][2] - t[2][2] ) 
      
     
     return diff
        
    }
    
    
    const count1=calculateDifference(s,square1); 
    
    const count2=calculateDifference(s,square2); 
    
    const count3=calculateDifference(s,square3); 
    
    const count4=calculateDifference(s,square4); 
    
    const count5=calculateDifference(s,square5); 
    
    const count6=calculateDifference(s,square6); 
    
    const count7=calculateDifference(s,square7); 
    
    const count8=calculateDifference(s,square8); 
    
    
    const counts = [count1,count2,count3, count4, count5, count6, count7, count8]
    
    
    
    return Math.min(...counts)
    
    }