Adobe Interview Question
Software Engineer / Developers#include<iostream>
#include<string>
using namespace std;
void permute(string s, int i = 0) {
if (i == s.size()) cout << s << endl;
else for (int j = i; j < s.size(); ++j) swap(s[i], s[j]), permute(s, i + 1), swap(s[i], s[j]);
}
you r really smart buddy. you made it look like a 2 line solution ;-). must say very elegant solution , excellent demonstration of power of recursion.
Good solution but one small criticism: don't put everything in one line; it is less readable. Nothing wrong with using 3 or 4 more lines to make your code more readable.
Sorry for the extra newlines...
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void doPermuteString(char in[], char out[], int used[], int length, int recurselev){
int i;
if(recurselev == length){
printf("%s\n", out);
return;
}
for(i=0;i<length;i++){
if(used[i]) continue;
out[recurselev] = in[i];
used[i] = 1;
doPermuteString(in, out, used, length, recurselev + 1);
used[i] = 0;
}
}
int permuteString(char string[]){
int i, length, *used;
char *out;
length = strlen(string);
out = (char *)malloc(sizeof(char) * (length + 1));
out[length] = '\0';
used = (int *)malloc(sizeof(int) * length);
for(i=0;i<length;i++){
used[i] = 0;
}
doPermuteString(string, out, used, length, 0);
free(out);
free(used);
return 1;
}
int main(){
char string[100];
scanf("%s", string);
permuteString(string);
return 0;
}
@arh are u an asshole ? no one ever said that whatever code you write has got to be a unique code in the world. You learn things from somewhere and if you like, you will reproduce it somewhere else...
The point is that *if* he took it from some source he should acknowledge it, otherwise it's IP theft.
May be its duplicate...but its tested
void swap(int *ar, int pos1, int pos2);
void permute(int *ar, int start, int ar_len);
main()
{
int ar[]={1,2,3,4,5,6,7,8}; /*Just as an example */
int len = 8;
permute(ar, 0, len);
return 0;
}
void swap(int *ar, int pos1, int pos2)
{
int temp = 0;
temp = ar[pos1];
ar[pos1]= ar[pos2];
ar[pos2] = temp;
}
void permute(int *ar, int start, int ar_len)
{
int i = 0, j = 0;
if (start == (ar_len-1)) {
while(i<ar_len){
printf("%d",ar[i++]);
}
printf("\n");
}
for (i=start; i<=(ar_len-1);i++) {
swap(ar, start, i);
j = 0;
permute(ar, start+1, ar_len);
swap(ar, start, i);
}
}
This code is on the same logic by which anyone will permute manually. Its intuitive !
Hold one character and permute others, proceed recursively.
- Ankit Gupta July 31, 2009