算法:解三階幻方

題目:3X3 的九宮格,每一個橫豎斜相加都等於15,使用1-9數字。express

要求:編程語言,1-9數字不重複。編程

function nMagic({ time = 3, sum = 15, from = 1, to = 9 } = {}) {
  const loop = ({
    results = [],
    arrs = [],
    time = 1,
    on = 1,
    from = 1,
    to = 4,
    fn = null
  }) => {
    for (let i = from; i <= to; i++) {
      let add = [].concat(arrs, i);
      if (on < time) {
        results = loop({
          results,
          arrs: add,
          time,
          on: on + 1,
          from,
          to,
          fn
        });
      } else {
        if (fn) {
          if (fn(add)) {
            results.push(add);
          }
        } else {
          results.push(add);
        }
      }
    }
    return results;
  };

  var expression = loop({
    time,
    from,
    to,
    fn(add) {
      let obc = {};
      let has = false;
      let n = 0;
      add.map(v => {
        if (obc[v]) has = true;
        else obc[v] = true;
        n += v;
      });
      return !has && n === sum;
    }
  });

  var combo = [];

  loop({
    time,
    from: 0,
    to: expression.length - 1,
    fn(add) {
      let no = false;

      let arr = [];
      let temp = [];
      let obc = {};
      add.map(v => {
        arr.push(expression[v]);
        temp = [].concat(temp, expression[v]);
      });

      // 是否重複項目
      temp.map(v => {
        if (obc[v]) no = true;
        else obc[v] = true;
      });
      if (no) return false;

      // 是否豎着的值知足條件
      for (let i = 0; i < time; i++) {
        let n = 0;
        arr.map(item => {
          n += item[i];
        });
        if (n !== sum) return false;
      }

      // 是否斜着的值知足條件
      let xiezhe1 = 0;
      let xiezhe2 = 0;
      arr.map((item, j) => {
        xiezhe1 += item[j];
        xiezhe2 += item[arr.length - j - 1];
      });
      if (xiezhe1 !== sum || xiezhe2 !== sum) return false;

      combo.push(arr);
      return true;
    }
  });

  return combo;
}
複製代碼
相關文章
相關標籤/搜索