Random Flip Matrix in C++

C++Server Side ProgrammingProgramming

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

 Live Demo

#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, ]
raja
Published on 02-May-2020 16:50:34
Advertisements