首页 > 解决方案 > 这个函数有多少种简化方式?

问题描述

我正在尝试简化/概括一个foo_one遍历多维数组并将除第一个子数组元素之外的所有子数组元素设置为具有null值的函数。

我只得到了第一个函数,然后我应该找到更多的方法来概括它,以仍然实现foo_one.

任何建议将不胜感激。

我已经实现了该功能的 2 个其他变体,如果可能的话,我希望拥有更多。

var arr = [
  [2, null, 2, null],
  [2, null, 2, null],
  [null, null, null, null],
  [null, null, null, null]
];

function foo_one() {
  for (let y = 0; y < arr.length - 1; y++) {
    for (let x = 0; x < arr.length - 1; x++) {
      if (arr[x + 1][y] != null) {
        if (arr[x + 1][y] == arr[x][y]) {
          arr[x][y] = arr[x][y] * 2;
          arr[x + 1][y] = null;
        }
        if (arr[x][y] == null) {
          arr[x][y] = arr[x + 1][y];
          arr[x + 1][y] = null;
        }
      }
    }
  }
}

function foo_two() {
  for (let y = 0; y < arr.length - 1; y++) {
    for (let x = 0; x < arr.length - 1; x++) {
      if (arr[x + 1][y] != null && arr[x + 1][y] == arr[x][y]) {
        arr[x][y] = arr[x][y] * 2;
        arr[x + 1][y] = null;
      }
    }
  }
}

function foo_three() {
  for (let y = 0; y < arr.length - 1; y++) {
    for (let x = 0; x < arr[y].length - 1; x++) {
      if (arr[x + 1][y] != null && arr[x + 1][y] == arr[x][y]) {
        arr[x][y] = arr[x][y] * 2;
        arr[x + 1][y] = null;
      }
    }
  }
}

// Output
[ [ 4, null, 4, null ],
  [ null, null, null, null ],
  [ null, null, null, null ],
  [ null, null, null, null ] ]

标签: javascriptarraysgeneralization

解决方案


下面的重写比原来的帖子更有效率。

let arr = [
    [2, null, 2, null],
    [2, null, 2, null],
    [null, null, null, null],
    [null, null, null, null]
];

function foo_four(arr) {
    for (let y = 0, yl = arr.length - 1; y < yl; y++) {
        let currRow = arr[y];
        let nextRow = arr[y + 1];

        for (let x = 0, xl = nextRow.length - 1; x < xl; x++) {
            let currValue = currRow[x];

            if (currValue && currValue === nextRow[x]) {
                currRow[x] = currValue * 2;
                nextRow[x] = null;
            }
        }
    }
}

foo_four(arr);
console.log(arr);
// [
//     [4, null, 4, null],
//     [null, null, null, null],
//     [null, null, null, null],
//     [null, null, null, null]
// ];

推荐阅读