formingMagicSquare.js

    0

    1

    The code in question creates a magic square of the given numbers. The magic square is represented by an array of strings, each of which is the sum of the squares of the given numbers. The function takes a single argument, the list of numbers to create the magic square.

    The cost function takes two arguments, the list of numbers and the squares array. It first returns the minimum value of the given list of numbers. If the list of numbers does not have a minimum value, then the cost function will return the empty list, which will be the sum of the squares of all the numbers in the list.

    Next, the cost function calculates the sum of the squares of the numbers in the list, using a loop that iterates over the list. If the number in the list is greater than the minimum value, then the cost function sets the minimum value to the number in the list and continues the loop. If the number in the list is not greater than the minimum value, then the cost function returns the empty list, which will be the sum of the squares of the numbers in the list.

    function formingMagicSquare(s) {
      const squares = ['618753294', '816357492', '834159672', '438951276', '672159834', '276951438', '294753618', '492357816'];
      let min = 100;
      let cost = (s, squares) => {
    
        return [...s.map(value => value.join('')).join('')].reduce((target, item, index) => {
          target += Math.abs(+item - +squares[index])
    
          return target;
        }, 0)
      };
    
      squares.forEach((item, index) => {
        let value = cost(s, squares[index]);
    
        (value < min) && (min = value);
      });
    
      return min;
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.