Categories
Array Leetcode Loop

Prison After N Days

let  prisonAfterNDays = function(cells, N) {

let cache = {},
counter = 1,
cycle = false,
len = 8;
let dup = [...cells];

function getNextCycle(data) {
let lastCycle = data[1];
let cycleDays = counter - lastCycle;
console.log(lastCycle, cycleDays);
let nextCycle = N - ((N - lastCycle) % cycleDays); //?.
// let nextCycle = counter; //?
// while (nextCycle + counter < N) {
// nextCycle = nextCycle += cycleDays;
// }

return nextCycle; //?
}

while(counter <= N) {
let key = dup.join(''),
data = cache[key],
row = [];

if (data && !cycle) {
cycle = true;
counter = getNextCycle(data);
}

if (data) {
dup = data[0];
counter++; //?
}
else {
for (let i = 0; i < len; i++) {
row[i] = dup[i - 1] === dup[i + 1] ? 1 : 0;
}
cache[key] = [[...row], counter];
dup = cache[key][0];
counter++; //?
}
}

return dup;
};

Leave a Reply

Your email address will not be published. Required fields are marked *