算法:解三阶幻方

2019-03-10  本文已影响0人  卡布奇诺的秘密_Me

题目:3X3 的九宫格,每个横竖斜相加都等于15,使用1-9数字。

要求:编程语言,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;
}
上一篇下一篇

猜你喜欢

热点阅读