Prison Cells After N Days
Problem statement
There are 8 prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
- If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
- Otherwise, it becomes vacant.
Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
You are given an integer array cells where cells[i] == 1 if the ith cell is occupied and cells[i] == 0 if the ith cell is vacant, and you are given an integer n.
Return the state of the prison after n days (i.e., n such changes described above).
Example 1:
Input: cells = [0,1,0,1,1,0,0,1], n = 7Output: [0,0,1,1,0,0,0,0]Explanation: The following table summarizes the state of the prison on each day:Day 0: [0, 1, 0, 1, 1, 0, 0, 1]Day 1: [0, 1, 1, 0, 0, 0, 0, 0]Day 2: [0, 0, 0, 0, 1, 1, 1, 0]Day 3: [0, 1, 1, 0, 0, 1, 0, 0]Day 4: [0, 0, 0, 0, 0, 1, 0, 0]Day 5: [0, 1, 1, 1, 0, 1, 0, 0]Day 6: [0, 0, 1, 0, 1, 1, 0, 0]Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
Example 2:
Input: cells = [1,0,0,1,0,0,1,0], n = 1000000000Output: [0,0,1,1,1,1,1,0]
Constraints:
cells.length == 8cells[i]is either0or1.1 <= n <= 109
My solution
/**
* @param {number[]} cells
* @param {number} N
* @return {number[]}
*/
var prisonAfterNDays = function(cells, N) {
const track = [];
let loopFrom;
for (let i =0; i<N; i++) {
let newCells = [...cells]
for (let j = 0; j < cells.length;j++) {
let left = cells[j - 1]
let right = cells[j + 1];
// console.log(j, left, right);
if (left === right) {
newCells[j] = 1;
} else {
newCells[j] = 0;
}
}
const str = newCells.join("")
if (!track.includes(str)) {
track.push(str)
} else {
loopFrom =i
// console.log(track.indexOf(str), str, i)
break;
}
cells = [...newCells];
}
if (!loopFrom) {
return cells;
} else {
const mod = N % loopFrom;
// console.log(mod, track, loopFrom)
return (track[mod - 1] || track[track.length - 1]).split("")
}
};
// 0,1,0,1,1,0,0,1 => 0
// 0,1,1,0,0,0,0,0