#include <iostream> #include <string.h> using namespace std; void shuffle(char* a) { bool done=true; int index = 0; int n = strlen(a); for(int i=0; i<n-1; i++) { if(a[i] == a[i+1]) { bool found = false; for(int j=i+2; j<n; j++) { if(a[j] != a[i+1]) { char r = a[j]; a[j] = a[i+1]; a[i+1] = r; found = true; break; } } if(!found) { done = false; } } } if(!done) { for(int i=n-1; i>0; i--) { if(a[i] == a[i-1]) { bool found = false; for(int j=i-2; j>=0; j--) { if(a[j] != a[i-1]) { char r = a[j]; a[j] = a[i-1]; a[i-1] = r; found = true; break; } } if(!found) { done = false; cout << "not possible\n"; } } } } } int main() { // your code goes here char s[100]; cin >> s; cout << "input: " << s <<endl; shuffle(s); cout << "output: " << s << endl; return 0; } input: ABBBCCCCCC not possible output: CCACBCBCBC input: ABBBCCCCC output: CACBCBCBC input: ABCDDDDDDABC output: ADBDCDADBDCD
This blog site is dedicated for articles on problem solving using C, C++, data structures, algorithms. Besides this few technical articles are also presented.
Jun 24, 2017
Given a string shuffle it such that no consecutive characters are same
Jun 23, 2017
print all permutations of given numbers for a set of size n
#include <iostream> using namespace std; void printArray(int b[], int size) { for(int i=0;i<size;i++) cout << b[i] << "-"; cout << endl; } void printPermutations(int n, int a[], int level) { if(n==0) { printArray(a, level); return; } for(int i=1; i<=3; i++) { a[level] = i; printPermutations(n-1, a, level+1); } } int main() { int n; int a[50]; cin >> n; printPermutations(n, a, 0); return 0; } Input: 3 Output: 1-1-1- 1-1-2- 1-1-3- 1-2-1- 1-2-2- 1-2-3- 1-3-1- 1-3-2- 1-3-3- 2-1-1- 2-1-2- 2-1-3- 2-2-1- 2-2-2- 2-2-3- 2-3-1- 2-3-2- 2-3-3- 3-1-1- 3-1-2- 3-1-3- 3-2-1- 3-2-2- 3-2-3- 3-3-1- 3-3-2- 3-3-3-
Subscribe to:
Posts (Atom)