I'm a high school student of grade 10 trying to work through some problems in a Data Structures and Algorithms book on Java.
One of the questions is to print all permutations of a string.
class C14
{
public static void main(char a[])
{
// char[] a = {'c','a','r','b','o','n'};
int c=0,w=0;
for(int q = 0;q<a.length;q++)
{
for(int i=0;i<a.length;i++)
{
for(int j=1;j<a.length;j++)
{
for(int k=1;k<a.length-1;k++)
{
for(int z=0;z<a.length;z++)
{
System.out.print(a[z]);
c++;
}
w++;
System.out.println();
char p=a[k+1];
a[k+1]=a[k];
a[k]=p;
}
System.out.println();
}
System.out.println();
char x=a[0];
a[0]=a[1];
a[1]=x;
}
}
System.out.println(" Character count = " + c);
System.out.println(" Word count = " + w);
}
}
This is my attempt. The book asks me to do it for the characters 'c','a','r','b','o','n'. My solution does just that, but when I try to use 3 or 4 letter words, it gives me repetitions. If I remove the outermost loop and try to print it, it works for 3 and 4 letter words but not for 5+ letter words.
I'll be glad to clarify my reasoning for it, I know it's not the most efficient, but do bear in mind the fact that I'm only in grade 10 and this is what came to my mind first.
Can someone please help me out, or at least hint at what's wrong? Please don't advise a recursive solution, because I want to work through it iteratively first. Thanks, Sumit.