0

6 つのタイプ(整数 0 ~ 5 として表される) の 60 個の項目 (6x10 として表される)でランダムに生成された配列がある場合、配列内で同じタイプのグループを検索するにはどうすればよいですか? (縦横に連結された 3 つ以上のグループ)

私は C++ や C に似たスクリプト環境 (LSL) で作業しています。

4

1 に答える 1

0

これは、コメント付きのパラメーター化された実際のJavaScript の例です。トリックは、配列を使用して、既にアクセスしたセル/ノードを示すことです。

var arr = [], visited, grp, val, rowLength = 6, threshold = 3;

// generate random array
for (var i = 0; i < 60; i++) {
  arr.push(Math.floor(Math.random() * 6));
}

alert(JSON.stringify(findGroups())); // executing the function and displaying the result.

function findGroups() {
  visited = []; // resetting visited
  var ret = []; // the return value is an array of groups
  for (var i = 0; i < arr.length; i++) {
    if (!visited[i]) {
      val = arr[i]; // set the value we are currently inspecting
      grp = []; // reset the current group
      flood(i); // the recursive flood function
      if (grp.length >= threshold) // add the group to the result if it meets the criteria 
        ret.push(grp);
    }
  }
  return ret;
}

function flood(idx) {
  if (visited[idx] || arr[idx] != val) // only look at cells with matching value...  
    return; // ... that weren't visited yet
  visited[idx] = true; // mark as visited
  grp.push(idx); // add index to current group
  if (idx % rowLength != 0) // can go left
    flood(idx - 1);
  if (idx % rowLength != rowLength - 1) // can go right
    flood(idx + 1);
  if (idx >= rowLength) // can go up
    flood(idx - rowLength);
  if (idx < arr.length - rowLength) // can go down
    flood(idx + rowLength);
}
于 2016-06-19T22:53:23.513 に答える