查找字符串数组

时间:2017-03-16 15:59:58

标签: javascript arrays

我想将数组中的相邻(垂直和水平)字符组合在一起,在这种情况下,所有相邻的" *"属于一个群体,见下文。然后我希望能够计算出多少组" *"在这种情况下,答案是3。

var x = ["...***....",
         "..*****...",
         "...***....",
         "........*.",
         ".......***",
         "..*.....*.",
         ".***......"];

代码:

function compareRows(){
    var totalGroups = 0;

    for (i = 0; i < x.length; i++) {        
        var array = x[i];

        for (j = 0; j < array.length; j++) {
            var row = array[j];

            for (k = 0; k < row.length; k++) {
                var char1 = row[k];
                var nextRow = j+1;
                var char2 = row[nextRow];

                if(char1== "*"){
                    if(char1 != char2) {
                            totalGroups+=1;
                    }
                } else {
                    //console.log("Keep searching..");
                }
            }
        }       
        } console.log(totalGroups); 
    }
    compareRows();

所以基本上每一行我都在寻找角色&#34; *&#34;当找到它时,如果下面一行中相同索引处的字符不是&#34; *&#34;,则找到一个组。但是,目前totalGroups为20,总数为&#34; *&#34;在整个阵列中找到。我觉得有点卡住而且不知道如何继续。

1 个答案:

答案 0 :(得分:1)

我相信你需要在找到星号的任何位置走网格,并跟踪你已经访问过的细胞。您可以使用visited数组执行此操作,以避免两次使用相同的单元格并执行递归遍历功能。这就是我能想到的:

const grid = [
  "...***....",
  "..*****...",
  "...***....",
  "........*.",
  ".......***",
  "..*.....*.",
  ".***......"
];

function getGroups(grid) {
  // split the grid into a 2d array of objects (cells)
  const cellGrid = grid.map((s, y) => s.split('').map((value, x) => ({value, x, y})));
  const height = cellGrid.length;
  const width = cellGrid[0].length;
  const visited = []; // keep track of visited cells
  const groups = [];
  let currentGroup = [];
  
  // walk each cell left-to-right top-to-bottom
  for(let y = 0; y < height; y++) {
    for(let x = 0; x < width; x++) {
      walkFromCell(x, y, true);
    }
  }
  
  return groups;
  
  function walkFromCell(x, y, groupStart) {
    const cell = getCell(x, y);
    // ignore visited and non-group cells
    if(!cell || cell.value !== '*' || visited.includes(cell)) return;

    currentGroup.push(cell);
    visited.push(cell);

    walkFromCell(x + 1, y, false);
    walkFromCell(x - 1, y, false);
    walkFromCell(x, y + 1, false);

    // groupStart is only true for the first cell in a group
    if(groupStart) {
      groups.push(currentGroup);
      currentGroup = [];
    }
  }
  
  function getCell(x, y) {
    return cellGrid[y] ? cellGrid[y][x] : null;
  }
}

const groups = getGroups(grid);
const groupCount = groups.length;
console.log(`Count = ${groupCount}`);
console.log('Groups =', groups);