【问题标题】:How to find the same values next to each other in multidimensional array?如何在多维数组中找到彼此相邻的相同值?
【发布时间】:2019-10-18 00:01:22
【问题描述】:

我尝试编写一个函数,该函数将在多维数组(值从 3 到 7)中找到至少 3 次彼此相邻的重复值(垂直和水平)。如果它发现,将其更改为不同的值。比方说 1。

我试图通过循环来做到这一点,但这似乎不是解决这个问题的好方法,或者我把它搞砸了。因为对于某些数组它有效,而对于某些数组则无效。

这是我的代码:

function searching(array) {
  for (i = 0; i < array.length; i++) {
    let horizontal = array[i][0];
    let howMany = 1;

    for (j = 1; j < array[i].length; j++) {
      if (horizontal === array[i][j]) {
        howMany += 1;
        horizontal = array[i][j];
        if (howMany >= 3) {
          for (d = j; d > j - howMany; d--) {
            array[i][d] = 0;
          }
        }
      } else {
        horizontal = array[i][j];
        howMany = 1;
      }

    }

  }


  for (v = 0; v < array.length; v++) {
    let vertical = array[0][v];
    let howMany = 1;
    for (x = 1; x < array.length; x++) {
      if (vertical === array[x][v]) {
        howMany++;
        vertical = array[x][v];
        if (howMany >= 3) {
          for (d = x; d > x - howMany; d--) {
            array[d][v] = 0;
          }
        }
      } else {
        vertical = array[x][v];
        howMany = 1;
      }
    }
  }
}

这个想法是例如给数组:

let array = [
    [3, 4, 5, 6, 7],
    [3, 4, 5, 6, 7],
    [3, 4, 5, 5, 5],
    [3, 5, 6, 7, 4]
  ]

结果应该是:

let result = [
    [1, 1, 1, 6, 7],
    [1, 1, 1, 6, 7],
    [1, 1, 1, 1, 1],
    [1, 5, 6, 7, 4]
  ]

在此先感谢您提供解决问题的任何想法 :) 问候!

【问题讨论】:

  • 6 出现了 3 次,为什么没有设置为 1?
  • 因为它不是相邻的另一个值 6 至少相邻重复 3 次。
  • 你说“对于某些 [arrays] 它不 [work]”。你能详细说明那些边缘情况吗?例如,边缘情况是否对相同值的垂直和水平序列相交的情况有问题?如果是这样,那么原因是您在将值用于计算其他序列之前覆盖了它们。您可以通过复制多维数组来解决这种极端情况,然后使用副本进行计算并使用原始数组覆盖值。

标签: javascript multidimensional-array


【解决方案1】:

一开始我没看懂这个问题... 所以这是我的代码:

let array = [
  [3, 4, 5, 6, 7],
  [3, 4, 5, 6, 7],
  [3, 4, 5, 5, 5],
  [3, 5, 6, 7, 4]
];

function replace(arr, target = 1) {
  let needToChange = []; // save the index to change
  const numbers = [3, 4, 5, 6, 7];
  const m = arr.length; // m rows
  const n = arr[0].length; // n columns

  let mi = 0;
  let ni = 0;

  // search in row
  for (mi = 0; mi < m; mi++) {
    for (let x = 0; x < numbers.length; x++) {
      const num = numbers[x]; // number to search
      let counter = 0; // counter for this number in row mi
      let tempArr = [];
      for (ni = 0; ni < n; ni++) {
        const currentNum = arr[mi][ni];
        if (currentNum === num) {
          counter++;
          tempArr.push([mi, ni]);
        }
      }
      if (counter >= 3) {
        needToChange = needToChange.concat(tempArr);
      }
    }
  }

  // search in column
  for (ni = 0; ni < n; ni++) {
    for (let x = 0; x < numbers.length; x++) {
      const num = numbers[x]; // number to search
      let counter = 0; // counter for this number in row mi
      let tempArr = [];
      for (mi = 0; mi < m; mi++) {
        const currentNum = arr[mi][ni];
        if (currentNum === num) {
          counter++;
          tempArr.push([mi, ni]);
        }
      }
      if (counter >= 3) {
        needToChange = needToChange.concat(tempArr);
      }
    }
  }

  // replace
  needToChange.forEach(([i, j]) => {
    array[i][j] = target;
  });
}

replace(array);
array.forEach(row => {
  console.log(row.join(', '));
})

【讨论】:

  • 您的输出不正确 - 按“运行代码 sn-p”
  • 问这个问题的是@Silarsf,而不是我
【解决方案2】:

您当前代码的问题是

(1) 您只检查单个行和列,当您需要同时检查它们时(例如,使用[[2, 2], [2, 5]],在起始位置[0][0] 时,您需要同时查看[0][1] (及其邻居,如果匹配)以及[1][0](及其邻居,如果匹配)。

(2) 此时您实际上并没有检查邻接,您只是在计算特定行或列中匹配元素的总数。

遍历数组的所有索引。如果已经检查过索引,请尽早返回。递归搜索该索引的邻居,如果总共找到至少 3 个匹配,则将它们全部设置为 1。将所有匹配的邻居放入 checked 集中以避免再次检查它们(即使相邻匹配少于 2 个)找到总数)。

setAllAdjacentToOne([
  [3, 4, 5, 6, 7],
  [3, 4, 5, 6, 7],
  [3, 4, 5, 5, 5],
  [3, 5, 6, 7, 4]
]);
// all 9s stay, the rest get set to 1:
setAllAdjacentToOne([
  [2, 2, 9, 7, 7],
  [2, 9, 9, 9, 7],
  [3, 4, 4, 5, 5],
  [9, 4, 5, 5, 9]
]);


function setAllAdjacentToOne(input) {
  const output = input.map(subarr => subarr.slice());
  const checked = new Set();
  const getKey = (x, y) => `${x}_${y}`;

  const width = input[0].length;
  const height = input.length;
  const getAllAdjacent = (x, y, numToFind, matches = []) => {
    if (x >= width || x < 0 || y >= height || y < 0) {
      return matches;
    }
    const key = getKey(x, y);
    if (!checked.has(key) && input[y][x] === numToFind) {
      checked.add(key);
      matches.push({ x, y });
      getAllAdjacent(x + 1, y, numToFind, matches);
      getAllAdjacent(x - 1, y, numToFind, matches);
      getAllAdjacent(x, y + 1, numToFind, matches);
      getAllAdjacent(x, y - 1, numToFind, matches);
    }
    return matches;
  };

  output.forEach((innerRowArr, y) => {
    innerRowArr.forEach((num, x) => {
      const allAdjacent = getAllAdjacent(x, y, num);
      if (allAdjacent.length <= 2) {
        return;
      }
      allAdjacent.forEach(({ x, y }) => {
        output[y][x] = 1;
      });
    });
  });
  console.log(JSON.stringify(output));
}

【讨论】:

    猜你喜欢
    • 2017-05-22
    • 1970-01-01
    • 2014-03-18
    • 2017-04-18
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    相关资源
    最近更新 更多