-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0957-prison-cells-after-n-days.js
More file actions
47 lines (40 loc) · 1.45 KB
/
0957-prison-cells-after-n-days.js
File metadata and controls
47 lines (40 loc) · 1.45 KB
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
/**
* Prison Cells After N Days
* Time Complexity: O(1)
* Space Complexity: O(1)
*/
var prisonAfterNDays = function (cells, n) {
const computeNextStateConfiguration = (currentConfiguration) => {
const nextConfiguration = new Array(8);
nextConfiguration[0] = 0;
nextConfiguration[7] = 0;
for (let position = 1; position < 7; position++) {
if (
currentConfiguration[position - 1] ===
currentConfiguration[position + 1]
) {
nextConfiguration[position] = 1;
} else {
nextConfiguration[position] = 0;
}
}
return nextConfiguration;
};
let simulationInputState = [...cells];
const sequenceOfStates = [];
const stateToSequenceIndex = new Map();
for (let dayNumber = 1; dayNumber <= n; dayNumber++) {
simulationInputState = computeNextStateConfiguration(simulationInputState);
const stateIdentifier = simulationInputState.join("");
if (stateToSequenceIndex.has(stateIdentifier)) {
const cycleStartIndex = stateToSequenceIndex.get(stateIdentifier);
const cyclePeriodLength = dayNumber - cycleStartIndex;
const remainingTargetDays = n - dayNumber;
const finalOffsetInCycle = remainingTargetDays % cyclePeriodLength;
return sequenceOfStates[cycleStartIndex + finalOffsetInCycle];
}
sequenceOfStates.push(simulationInputState);
stateToSequenceIndex.set(stateIdentifier, sequenceOfStates.length - 1);
}
return simulationInputState;
};