0

If I have a randomly generated array with 60 items (represented as 6x10) of 6 types (represented as integers 0-5), how can I search for groups of the same type within the array? (Vertically/horizontally connected groups of at least 3.)

I'm working in a scripting environment (LSL) similar to C++ and C.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
F8bit
  • 3
  • 2
  • 1
    Use a flood fill algorithm. – nemetroid Jun 19 '16 at 17:43
  • What I have theorized in my head is somehow determine a starting point somewhere along the array, then begin loops in each "direction," but this could quickly escalate into dozens of loops with larger grids as each connected type would need its own loops. _(No actual code has been written by me yet on this department as I am at a loss.)_ – F8bit Jun 19 '16 at 17:45
  • 1
    LSL isn't at all similar to C which is not a scripting language, LSL is more similar to Javascript - such as its string handling. – Weather Vane Jun 19 '16 at 17:49
  • @WeatherVane You are correct; Poor wording on my part. The languages aren't inherently similar in function, only syntax. – F8bit Jun 19 '16 at 17:56
  • Your clue is in the flood fill. – Weather Vane Jun 19 '16 at 18:12

1 Answers1

0

Here is a parametrized working javascript example with comments, the trick is to use an array to denote the cells / nodes you have already visited.

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);
}
maraca
  • 8,468
  • 3
  • 23
  • 45
  • Thank you for the code example. With some changes in functionality I've been able to successfully implement this, and I think I've figured out how to properly use recursive functions. – F8bit Jun 21 '16 at 09:16