Guruji Interview Question
Software Engineer / DevelopersHere is the code.
Given: "1234" and N = 2
It would print out "13", "14", "24"
all other strings ("43","41"..) are just permutation of the above result.
Working code. Just copy and paste it to your favorite IDE then compile away.
#include <iostream>
#include <string>
void printComb(const char ar[], bool used[], int SIZE){
string str = "";
for (int i = 0; i < SIZE; ++i){
if (used[i]){
str += ar[i];
}
}
cout << str << endl;
}
//variable u keeps track of the number of
//characters in our result
void comb(const char ar[], bool used[], int index, int u, int N, int SIZE){
if (u == N){
printComb(ar, used, SIZE);
} else if (index >= SIZE){
return;
} else {
used[index] = true;
++u;
comb(ar, used, index + 2, u, N, SIZE);
used[index] = false;
--u;
comb(ar, used, index + 1, u, N, SIZE);
}
}
int main(){
int N = 2;
string str = "1234";
bool used[str.length()];
for (int i = 0; i < str.length(); ++i){
used[i] = false;
}
comb(str.c_str(), used, 0, 0, N, str.length());
}
is {1, 3, 10} and {10, 1, 3} equivalent? Should both be print out?
- vodangkhoa April 22, 2007