Circular Permutation in Binary Representation in C++

C++Server Side ProgrammingProgramming

Suppose we have 2 integers n and start. Our task is return any permutation p of (0,1,2.....,2^n -1) as follows −

  • p[0] = start
  • p[i] and p[i+1] differ by only one bit in their binary representation.
  • p[0] and p[2^n -1] must also differ by only one bit in their binary representation.

So if the input is like n = 2 and start = 3, then the returned array will be [3,2,0,1], these are [11,10,00,01]

To solve this, we will follow these steps −

  • ans is an array
  • for i in range 0 to 2^n
    • insert start XOR i XOR i/2 into ans
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
         cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector<int> circularPermutation(int n, int start) {
      vector <int> ans;
      for(int i = 0 ; i < 1<<n; i++){
         ans.push_back(start ^ i ^(i>>1));
      }
      return ans;
   }
};
main(){
   Solution ob;
   print_vector(ob.circularPermutation(5,3));
}

Input

5
3

Output

[3, 2, 0, 1, 5, 4, 6, 7, 15, 14, 12, 13, 9, 8, 10, 11, 27, 26, 24, 25, 29, 28, 
30, 31, 23, 22, 20, 21, 17, 16, 18, 19, ]
raja
Published on 02-May-2020 11:30:04
Advertisements