forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrison Cells After N Days.js
53 lines (43 loc) · 1.04 KB
/
Prison Cells After N Days.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* @param {number[]} cells
* @param {number} n
* @return {number[]}
*/
var prisonAfterNDays = function(cells, n) {
const set = new Set()
let cycleDuration = 0
while(n--) {
const nextCells = getNextCells(cells)
// 1. Get cycle length
if(!set.has(String(nextCells))){
set.add(String(nextCells))
cycleDuration++
cells = nextCells
} else {
// 2. Use cycle length to iterate once more to get to correct order
let remainderToMove = n%cycleDuration
while(remainderToMove >= 0) {
remainderToMove--
cells = getNextCells(cells)
}
break
}
}
return cells
};
function getNextCells(cells) {
let temp = [...cells]
for(let i = 0; i < 8; i++) {
if(i>0 && i < 7 && cells[i-1] === cells[i+1]) {
temp[i] = 1
} else {
temp[i] = 0
}
}
return temp
}
// 0
// 1
// 2
// n
// 1 000 000 % n