1

So I'm trying to make a magic square with min changes, but with this i only get the last option, I mean is a magic square but not with the min, I was thinking that somehow we can use the min value of x as an indicator to change into that specific array, but not sure how to do that.

function minChange(arr) {
  
  let ms = [
    [[4, 3, 8], [9, 5, 1], [2, 7, 6]],
    [[6, 1, 8], [7, 5, 3], [2, 9, 4]],
    [[2, 7, 6], [9, 5, 1], [4, 3, 8]],
    [[2, 9, 4], [7, 5, 3], [6, 1, 8]],
    [[8, 1, 6], [3, 5, 7], [4, 9, 2]],
    [[8, 3, 4], [1, 5, 9], [6, 7, 2]],
    [[6, 7, 2], [1, 5, 9], [8, 3, 4]],
    [[4, 9, 2], [3, 5, 7], [8, 1, 6]]
  ];

  function magic(arr, ms) {
    let count = 0;
    for (let i = 0; i < 3; i++) {
      for (let j = 0; j < 3; j++) {
        if (arr[i][j] != ms[i][j])
          count++;
      }
    }
    return count;
  }
  // If all the elements need to be changed,
  // there would be 9 changes, so we take the
  // max as 9
  let min = 9;
  for (let i = 0; i < 8; i++) {
    let x = magic(arr, ms[i]);
    if (x < min){
      x = min;
      arr = ms[i].slice();
      }
  }
  return arr;
}

let arr = [[4, 9, 2], [3, 5, 7], [8, 1, 5]];
console.log(minChange(arr));

2 Answers2

0
function magic(s) {
    const possible_square = [
        [[8, 3, 4], [1, 5, 9], [6, 7, 2]], 
        [[6, 7, 2], [1, 5, 9], [8, 3, 4]], 
        [[4, 3, 8], [9, 5, 1], [2, 7, 6]], 
        [[2, 7, 6], [9, 5, 1], [4, 3, 8]], 
        [[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]]
    ];

    let cost = null;
    let min = 8;
  
    for (let a = 0; a < min; a ++) {
      let temp = 0;
      temp = Math.abs(s[0][0] - possible_square[a][0][0]) + Math.abs(s[0][1] - possible_square[a][0][1]) + Math.abs(s[0][2] - possible_square[a][0][2]);
      temp += Math.abs(s[1][0] - possible_square[a][1][0]) + Math.abs(s[1][1] - possible_square[a][1][1]) + Math.abs(s[1][2] - possible_square[a][1][2]);
      temp += Math.abs(s[2][0] - possible_square[a][2][0]) + Math.abs(s[2][1] - possible_square[a][2][1]) + Math.abs(s[2][2] - possible_square[a][2][2]);
  
      if (cost === null) {
        cost = temp;
      }
  
      if (cost !== null) {
        if (temp < cost) {
          cost = temp;
        }
      }
    }
  
    return cost;
}
  • Please add a few words describing how You solution solves the problem and what it was, instead of just provide an answer, if you want to help develop undertanding – T. Nielsen Jul 29 '22 at 12:18
0

You have a wrong assignment here:

  if (x < min){
      x = min;
      arr = ms[i].slice();
  }

It should be:

  if (x < min){
      min = x;
      arr = ms[i].slice();
  }
trincot
  • 317,000
  • 35
  • 244
  • 286