Skip to content

Commit c0dd972

Browse files
authored
Create random-flip-matrix.cpp
1 parent fe52cc8 commit c0dd972

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

C++/random-flip-matrix.cpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Time: O(1)
2+
// Space: O(min(f, r * c))
3+
4+
class Solution {
5+
public:
6+
Solution(int n_rows, int n_cols) :
7+
n_rows_(n_rows),
8+
n_cols_(n_cols),
9+
n_(n_rows * n_cols),
10+
gen_{(random_device())()} {
11+
12+
}
13+
14+
vector<int> flip() {
15+
uniform_int_distribution<int> uni(0, --n_);
16+
const auto target = uni(gen_);
17+
int x = get(target, target);
18+
lookup_[target] = get(n_, n_);
19+
return {x / n_cols_, x % n_cols_};
20+
}
21+
22+
void reset() {
23+
lookup_.clear();
24+
n_ = n_rows_ * n_cols_;
25+
}
26+
27+
private:
28+
int get(int key, int default_value) {
29+
return lookup_.count(key) ? lookup_[key] : default_value;
30+
}
31+
32+
int n_rows_;
33+
int n_cols_;
34+
int n_;
35+
unordered_map<int, int> lookup_;
36+
default_random_engine gen_;
37+
};
38+
39+
/**
40+
* Your Solution object will be instantiated and called as such:
41+
* Solution obj = new Solution(n_rows, n_cols);
42+
* vector<int> param_1 = obj.flip();
43+
* obj.reset();
44+
*/
45+

0 commit comments

Comments
 (0)