ActiveTrak Subregions2

by Matthew Vasallo

JavaScript

const input = [
  [5, 0, 25, 5, 145, 250],
  [0, 5, 95, 115, 165, 250],
  [15, 5, 175, 250, 185, 160],
  [5, 0, 145, 250, 245, 140],
  [115, 210, 60, 5, 230, 220],
  [0, 80, 45, 95, 170, 145],
];

const findCellAboveThreshold = (grid, threshold) => {
    const cellsThatMatch = []
    for (let y = input.length - 1; y >= 0; y--) {
        for (let x = 0; x < input[y].length; x++) {
            const cellValue = input[y][x]
            if (cellValue > threshold) {
                console.log(`hit cell{ ${x}, ${input[y].length - y - 1}}`)
                cellsThatMatch.push({
                    threshold: cellValue, x, y: input[y].length - y - 1,
                })
            }
        }
    }
    return cellsThatMatch
}

const cellsAreAdjacent = (cellA, cellB) => Math.max(Math.abs(cellA.x - cellB.x), Math.abs(cellA.y - cellB.y)) === 1;

const cellIsInRegion = (cellToCheck, region) => region.some((cell) => cellsAreAdjacent(cell, cellToCheck));

const findRegionCellIsIn = (cellToCheck, regions) => regions.find(region => cellIsInRegion(cellToCheck, region));

const findRegions = (cells) => {
    const alreadyInRegion = new Set();
    const cellRegionMap = new Map();
    const regions = [];
    for (let i = 0; i < cells.length; i++) {
        const cell = cells[i];
        const cellKey = `${cell.x}.${cell.y}`;
        if (!cellRegionMap.has(cellKey)) {
            const currentRegion = [cell];
            alreadyInRegion.add(cellKey);
            for (let j = i + 1; j < cells.length; j++) {
                const otherCell = cells[j];
                const otherCellKey = `${cell.x}.${cell.y}`;
                if (cellsAreAdjacent(cell, otherCell)) {
                  currentRegion.push(otherCell);
                  alreadyInRegion.add(otherCellKey);
                }
            }
            regions.push(currentRegion);
        }
    }
}

const cellsAboveThreshold = findCellAboveThreshold(input, 200);
/* console.log(cellsAboveThreshold); */
const regions =...