Monday, September 27, 2021

Binary string permutations

Previously, I had solved printing all permutations of a string. As part of a programming contest, I solved binary string permutations using C++. What is interesting in this solution is that is uses a simple for loop and obtains each binary permutation by converting a decimal number to a binary number:

//Print all binary string combinations of length n.
//You can think of the strings as binary forms of numbers from 0 to 2^n-1.
//Solution of https://www.algoleague.com/contest/algorithm-training-beginner-set/problem/the-pit/detail
//Şamil Korkmaz, 27.09.2021
#include <iostream>
using namespace std;
//Convert decimal number to binary number string
void dec2binStr(int dec, const int n) {
//printf("-------\n");
char s[n+1];
s[n] = 0; //end of line character
for(int i=0; i < n; i++) {
//printf("dec = %d\n", dec);
int digit = dec & 1; //get rightmost digit
dec = dec >> 1; //divide by 2
//printf("digit = %d\n", digit);
s[n-1-i] = digit + 48; //ascii '0' = 48
//printf("digit = %d\n", digit);
}
cout << s << endl;
}
int main() {
int n; cin >> n;
//int n = 4;
int maxVal = 1 << n; //2^n
//printf("maxVal = %d\n", maxVal);
for(int i = 0; i < maxVal; i++) { //numbers from 0 to 2^n-1
dec2binStr(i, n);
//cout << "s = " << s << endl;
}
return 0;
}

No comments:

Post a Comment