forked from adamespii/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem_141.js
83 lines (74 loc) Β· 1.8 KB
/
problem_141.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class ThreeStack {
/**
* Create three stacks usings single list
* @param {number} [stackCapacity=3]
*/
constructor(stackCapacity = 3) {
this.stackCapacity = stackCapacity;
this.values = [];
this.sizes = [0, 0, 0];
this.numberOfStacks = 3;
}
/**
* Pop top element off stack (1-3)
* @param {number} numStack
* @return {number}
*/
pop(numStack) {
if (this.isEmpty(numStack)) {
return null;
}
const topIndex = this.indexOfTop(numStack);
const value = this.values[topIndex];
this.values[topIndex] = 0; // Clear out element
this.sizes[numStack]--; // Reduce num elements in the stack
return value;
}
/**
* Pushes elements into stack
* @param {*} item
* @param {number} numStack
*/
push(item, numStack) {
if (this.isFull(numStack)) {
return;
}
// Add one to the respective stack count
this.sizes[numStack - 1]++;
// Add the value to the list
this.values[this.indexOfTop(numStack)] = item;
}
/**
* Index of the top element
* @param {number} numStack
* @return {number}
*/
indexOfTop(numStack) {
const offset = numStack * this.stackCapacity; // Find the starting point in the array
const size = this.sizes[numStack - 1]; // How many elements are in that stack currently?
return offset + size - 1;
}
/**
* Returns stack capacity
* @return {number}
*/
getStackCapacity() {
return this.stackCapacity;
}
/**
* Checks if the stack is full
* @param {number} numStack
* @return {boolean}
*/
isFull(numStack) {
return this.sizes[numStack - 1] === this.stackCapacity;
}
/**
* Checks if a stack is empty
* @param {number} numStack
* @return {boolean}
*/
isEmpty(numStack) {
return this.sizes[numStack - 1] === 0;
}
}