This marvelous code is implemented and provided by "Riya Tyagi" from Galgotias College, Greater Noida.
Note : Save this code inside Combinations.java file inside Eclipse IDE
import java.util.Scanner;
public class Combinations
{
// method to find factorial of number
static int factorial(int num)
{
if (num == 0)
return 1;
return num * factorial(num - 1);
}
// recursive method to find all permutations of given string
static String[] permutations(String x)
{
String[] a;
// base case to stop the recursion
if (x.length() >= 1)
{
a = new String[factorial(x.length())];
int k = 0;
for (int i = 0; i < x.length(); i++)
{
String[] b;
if (i > 0)
{
String t = x.substring(0, i).
concat(x.substring(i + 1, x.length()));
b = permutations(t); // call this method recursively
}
else
{
String t = x.substring(1, x.length());
b = permutations(t);
}
for (int j = 0; j < b.length; j++)
{
a[k] = String.valueOf(x.charAt(i)).concat(b[j]);
k++;
}
} // end of for loop
} // end of if
else
{
a = new String[1];
a[0] = "";
}
return a;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Input a string for its combinations: ");
String x = sc.next();
System.out.println("# output #");
String[] a = Combinations.permutations(x);
for (int i = 0; i < a.length; i++)
{
System.out.println((i + 1) + " : " + a[i]);
}
} // end of main method
} // end of class
Note : Save this code inside Combinations.java file inside Eclipse IDE
import java.util.Scanner;
public class Combinations
{
// method to find factorial of number
static int factorial(int num)
{
if (num == 0)
return 1;
return num * factorial(num - 1);
}
// recursive method to find all permutations of given string
static String[] permutations(String x)
{
String[] a;
// base case to stop the recursion
if (x.length() >= 1)
{
a = new String[factorial(x.length())];
int k = 0;
for (int i = 0; i < x.length(); i++)
{
String[] b;
if (i > 0)
{
String t = x.substring(0, i).
concat(x.substring(i + 1, x.length()));
b = permutations(t); // call this method recursively
}
else
{
String t = x.substring(1, x.length());
b = permutations(t);
}
for (int j = 0; j < b.length; j++)
{
a[k] = String.valueOf(x.charAt(i)).concat(b[j]);
k++;
}
} // end of for loop
} // end of if
else
{
a = new String[1];
a[0] = "";
}
return a;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Input a string for its combinations: ");
String x = sc.next();
System.out.println("# output #");
String[] a = Combinations.permutations(x);
for (int i = 0; i < a.length; i++)
{
System.out.println((i + 1) + " : " + a[i]);
}
} // end of main method
} // end of class
great sir
ReplyDeleteYeh baaaat....
ReplyDeleteThanks sir
ReplyDelete