Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Rearranger {
- /**
- * Program: Rearranger.java
- * Purpose: Re-arrange the letters of a word (up to 10 letters) every possible way.
- * Creator: Chris Clarke
- * Created: 20.07.2015
- */
- private static int c = 0; // counts the number of different variations
- private static String[] theArray; // for displaying each string permutation
- public static void main(String[] args) {
- final int MAX = 10; // maximum length of string
- Scanner scan = new Scanner(System.in); // reads keyboard input
- String s = null;
- // example: s = "0123456789"
- // assign to s the command line argument, if any
- if (args.length>0) {
- s = args[0];
- } else {
- // prompt user for input
- System.out.print("Enter a string (up to "+MAX+" characters long): ");
- // assign to s the String entered by the user
- s = scan.next();
- }//if
- // to avoid excessive runtime/memory usage
- if (s.length()>MAX) {
- System.out.println("String too long! Max "+MAX+" characters.");
- return; // exit program
- }//if
- // no. of permutations is factorial of string length
- theArray = new String[factorial(s.length())];
- // method call to display each permutation
- displayString(s);
- System.out.println("\nThere are "+c+" permutations/re-arrangements of \""+s+"\".");
- }//main()
- public static void displayString(String s) {
- displayString("", s);
- }//displayString(String)
- private static void displayString(String prefix, String s) {
- int n = s.length();
- if (n == 0) {
- // print solution
- System.out.print(prefix+"\t");
- theArray[c++] = prefix;
- } else {
- for (int i=0; i<n; i++) {
- // recursive method call
- displayString(prefix+s.charAt(i), s.substring(0, i)+s.substring(i+1, n));
- }//for
- }//if
- }//displayString(String, String)
- public static int factorial(int n) {
- return (n == 1)? 1: n * factorial(n - 1);
- }//factorial()
- }//class Rearranger
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement