-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0519-random-flip-matrix.js
More file actions
45 lines (38 loc) · 1.2 KB
/
0519-random-flip-matrix.js
File metadata and controls
45 lines (38 loc) · 1.2 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
/**
* Random Flip Matrix
* Time Complexity: O(1)
* Space Complexity: O(K)
*/
var Solution = function (m, n) {
this.matrixRows = m;
this.matrixColumns = n;
this.currentTotalAvailable = m * n;
this.indexMap = new Map();
};
Solution.prototype.flip = function () {
const randomChosenIndex = Math.floor(
Math.random() * this.currentTotalAvailable,
);
let resultantMatrixIndex;
if (this.indexMap.has(randomChosenIndex)) {
resultantMatrixIndex = this.indexMap.get(randomChosenIndex);
} else {
resultantMatrixIndex = randomChosenIndex;
}
const lastValidSlotIndex = this.currentTotalAvailable - 1;
let valueToMove;
if (this.indexMap.has(lastValidSlotIndex)) {
valueToMove = this.indexMap.get(lastValidSlotIndex);
} else {
valueToMove = lastValidSlotIndex;
}
this.indexMap.set(randomChosenIndex, valueToMove);
this.currentTotalAvailable--;
const resultingRow = Math.floor(resultantMatrixIndex / this.matrixColumns);
const resultingColumn = resultantMatrixIndex % this.matrixColumns;
return [resultingRow, resultingColumn];
};
Solution.prototype.reset = function () {
this.currentTotalAvailable = this.matrixRows * this.matrixColumns;
this.indexMap.clear();
};