Adobe Amazon Interview Question
Development Support Engineersvoid permute(char s[],int k)
{
if(i==strlen(s))
cout<<s<<endl;
else
for(int j=0;j<strlen(s);++j)
{
swap(s[k],s[j]);
permute(s,k+1);
swap(s[k],s[j]);
}
}
int main()
{
char s1[5]="hello";
permute(s1,0);
return 0;
}
You didn't declare "i" in permute function and your char array s1 is too short for string "hello".
This code does not take into consideration the second condition.
If the input string is "aaaaa" this program will give "aaaaa" 5 factorial times but actually it shoud give only once.
Here is what I wrote for integers -- basically same thing.
To calculate the permutation of an array of objects, foreach object in the array, add the object to the permutations of the reminder of the group recursively.
public ArrayList<ArrayList<Integer>> findPermutations(ArrayList<Integer> integers)
{
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (integers == null || integers.size() == 0)
{
return result;
}
for (int i = 0; i < integers.size(); i++)
{
ArrayList<Integer> subArray = new ArrayList<Integer>();
for (int j = 0; j < integers.size(); j++)
{
if (!integers.get(j).equals(integers.get(i)))
{
subArray.add(integers.get(j));
}
}
ArrayList<ArrayList<Integer>> subResult = this.findPermutations(subArray);
for (ArrayList<Integer> subPerm : subResult)
{
subPerm.add(integers.get(i));
result.add(subPerm);
}
ArrayList<Integer> selfResult = new ArrayList<Integer>();
selfResult.add(integers.get(i));
result.add(selfResult);
}
return result;
}
So for [1, 2, 3, 4] you'll get
[4, 3, 2, 1]
[3, 2, 1]
[3, 4, 2, 1]
[4, 2, 1]
[2, 1]
[4, 2, 3, 1]
[2, 3, 1]
[2, 4, 3, 1]
[4, 3, 1]
[3, 1]
[3, 2, 4, 1]
[2, 4, 1]
[2, 3, 4, 1]
[3, 4, 1]
[4, 1]
[1]
[4, 3, 1, 2]
[3, 1, 2]
[3, 4, 1, 2]
[4, 1, 2]
[1, 2]
[4, 1, 3, 2]
[1, 3, 2]
[1, 4, 3, 2]
[4, 3, 2]
[3, 2]
[3, 1, 4, 2]
[1, 4, 2]
[1, 3, 4, 2]
[3, 4, 2]
[4, 2]
[2]
[4, 2, 1, 3]
[2, 1, 3]
[2, 4, 1, 3]
[4, 1, 3]
[1, 3]
[4, 1, 2, 3]
[1, 2, 3]
[1, 4, 2, 3]
[4, 2, 3]
[2, 3]
[2, 1, 4, 3]
[1, 4, 3]
[1, 2, 4, 3]
[2, 4, 3]
[4, 3]
[3]
[3, 2, 1, 4]
[2, 1, 4]
[2, 3, 1, 4]
[3, 1, 4]
[1, 4]
[3, 1, 2, 4]
[1, 2, 4]
[1, 3, 2, 4]
[3, 2, 4]
[2, 4]
[2, 1, 3, 4]
[1, 3, 4]
[1, 2, 3, 4]
[2, 3, 4]
[3, 4]
[4]
public class Permutation2 {
public static void main(String[] args)
{
char[] a = "aa".toCharArray();
Permutation2 p = new Permutation2();
p.permutation(a,a.length);
}
public void permutation(char[] a, int n) {
if(n == 1){
System.out.println(a);
return;
}
boolean[] b = new boolean[256];
for(int i = 0; i < n; i++){
if(b[(int)a[i]])continue;
b[(int)a[i]]=true;
swap(a, i, n-1);
permutation(a, n-1);
swap(a, i, n-1);
}
}
private void swap(char[] a, int i, int j) {
char c;
c = a[i]; a[i] = a[j]; a[j] = c;
}
}
- marcelovox2 October 13, 2012