ActiveTrak Subregions3

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 input2 = [
  [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) {
                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 getCellKey = cell => `${cell.x},${cell.y}`;

const calculateCenterOfMass = region => {
    const weightedSums = region.reduce((acc, currentCell) => {
        acc.x += (currentCell.x * currentCell.threshold);
        acc.y += (currentCell.y * currentCell.threshold);
        acc.threshold += currentCell.threshold;
        return acc;
    }, {x: 0, y: 0, threshold: 0});
    return {
        x: weightedSums.x / weightedSums.threshold, y: weightedSums.y / weightedSums.threshold
    };
};

const findRegions = (cells) => {
    const regions = []
    const cellRegionIndexMap = new Map();
    while (cells.length > 0) {
        const currentCell = cells.pop();
        const currentCellKey = getCellKey(currentCell);
        //If current cell isn't in region, then create region
        if (!cellRegionIndexMap.has(currentCellKey)) {
            regions.push([currentCell])
            cellRegionIndexMap.set(currentCellKey, regions.length - 1);
        }

        const currentRegionIndex =...