- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Random Flip Matrix in C++
Suppose we have a binary matrix with n_rows number of rows and n_cols number of columns. Here all values are initially 0. we have to define a function flip() which chooses a 0 value uniformly at random, changes it to 1, and then returns the position [row.id, col.id] of that value. Also, we have to write another function reset() which sets all values back to 0. We have to try to minimize the number of calls to system's Math.random() and optimize the time and space complexity.
If we have the matrix of order 2x3, and we call flip four times, then the result will be [0,1], [1,2], [1,0], [1,1].
To solve this, we will follow these steps −
- Make a map called holes,
- In the initializer, do the following
- initialize random number generator, n := number of rows, m := number of cols,
- size := n * m
- In the flip method, do the following −
- id := random number mod size, decrease size by 1, rid := id
- if id is present in holes, then id := holes[id]
- holes[rid] := holes[size] when size in holes otherwise size
- return a pair (id / m, id mod m)
- In the reset method, do
- size := n x m, and clear the holes
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; void print_vector(vector<int> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: unordered_map <int, int> holes; int n; int m; int size; Solution(int n_rows, int n_cols) { srand(time(NULL)); n = n_rows; m = n_cols; size = n * m; } vector<int> flip() { int id = rand() % size; size--; int rid = id; if(holes.count(id)){ id = holes[id]; } holes[rid] = holes.count(size) ? holes[size] : size; return {id / m, id % m}; } void reset() { size = n * m; holes.clear(); } }; main(){ Solution ob(2,2); print_vector(ob.flip()); print_vector(ob.flip()); print_vector(ob.flip()); print_vector(ob.flip()); }
Input
Initialize the constructor using 2,2 and call flip four times
Output
[1, 1, ] [0, 0, ] [1, 0, ] [0, 1, ]
Advertisements