// Version 1 simple logic (uses nested for loops)
class ShuffleString
{
public static void main(String as[])
{
char s[]={'a','b','c'};
int i,j,k,n=s.length;
/* number of for loops should match with number of character i.e here ‘3’ */
for(i=0;i
for(j=0;j
for(k=0;k
if(i!=j && j!=k && i!=k)
System.out.println(s[i]+","+s[j]+","+s[k]);
}
}
/* Output: */
abc
acb
bac
bca
cab
cba
// Version 2 for the same program (uses recursive logic)
class ShuffleString
{
static char s[]={'a','b','c'};
public static void main(String as[])
{
shuffle(s.length);
}
public static void shuffle(int n)
{
int i;
char t;
if(n==1)
System.out.println(new String(s));
else
{
for(i=0;i
{
t=s[i];
s[i]=s[n-1];
s[n-1]=t;
shuffle(n-1);
t=s[n-1];
s[n-1]=s[i];
s[i]=t;
}
}
}
}
/* Output: */
bca
cba
cab
acb
bac
abc
0 comments:
Post a Comment