Search code examples
algorithmflood-filllinden-scripting-language

Finding groups in a single-dimensional grid array


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.


Solution

  • 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);
    }