Infection Programming Exercise

by Matthew Vasallo

JavaScript

/* Let a n*m grid represents a population resistance to a bacterial infection. 
The infection begins at a random cell, and spreads horizontally and vertically (Not diagonally) to any adjacent cell that has an infection resistance less or equals to the value of the source infected cell. Infected cells can then infect their neighbors according to the same rules.
For this exercise, assume we have access to a Cell class with the following methods:
getNeighbors(), which returns a list of neighboring cells- This method handles the grid boundaries and guarantees to never get out of bound.
getResistance(), which returns the infection resistance value of the cell
The following grid shows an example infection propagation starting at the highlighted cell with value 9
 */




const findInfectedCells = firstInfectedCell => {
  let infectedCells = new Set([firstInfectedCell]);
  let neighbordsToConsider = [firstInfectedCell];

  while (neighbordsToConsider.length > 0) {
  let currentCell = neighbordsToConsider.pop();
    currentCell.getNeighbors().forEach(neighborCell => {
      if (!infectedCells.has(neighborCell) && neighborCell.getResistance() < currentCell.getResistance()) {
        infectedCells.add(neighborCell);
        neighbordsToConsider.push(neighborCell);
      }
    });
  }

/*   const traverseNeighbors = currentCell => {
    currentCell.getNeighbors().forEach(neighborCell => {
      if (!infectedCells.has(neighborCell) && neighborCell.getResistance() < currentCell.getResistance()) {
        infectedCells.add(neighborCell);
        traverseNeighbors(neighborCell);
      }
    });
   */
    traverseNeighbors(firstInfectedCell);
  };

  return infectedCells;
};