Advertisement
brilliant_moves

Rearranger.java

Jul 19th, 2015
399
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 2.15 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Rearranger {
  4.  
  5.    /**
  6.    *    Program:    Rearranger.java
  7.    *    Purpose:    Re-arrange the letters of a word (up to 10 letters) every possible way.
  8.    *    Creator:    Chris Clarke
  9.    *    Created:    20.07.2015
  10.    */
  11.    
  12.    private static int c = 0;        // counts the number of different variations
  13.    private static String[] theArray;    // for displaying each string permutation
  14.    
  15.    public static void main(String[] args) {
  16.  
  17.       final int MAX = 10; // maximum length of string
  18.       Scanner scan = new Scanner(System.in); // reads keyboard input
  19.       String s = null;
  20.  
  21.       // example: s = "0123456789"
  22.      
  23.       // assign to s the command line argument, if any
  24.       if (args.length>0) {
  25.          s = args[0];
  26.       } else {
  27.          // prompt user for input
  28.          System.out.print("Enter a string (up to "+MAX+" characters long): ");
  29.          // assign to s the String entered by the user
  30.          s = scan.next();
  31.       }//if
  32.      
  33.       // to avoid excessive runtime/memory usage
  34.       if (s.length()>MAX) {
  35.          System.out.println("String too long! Max "+MAX+" characters.");
  36.          return; // exit program
  37.       }//if
  38.      
  39.       // no. of permutations is factorial of string length
  40.       theArray = new String[factorial(s.length())];
  41.  
  42.       // method call to display each permutation
  43.       displayString(s);
  44.       System.out.println("\nThere are "+c+" permutations/re-arrangements of \""+s+"\".");
  45.    }//main()
  46.  
  47.    public static void displayString(String s) {
  48.       displayString("", s);
  49.    }//displayString(String)
  50.  
  51.    private static void displayString(String prefix, String s) {
  52.       int n = s.length();
  53.       if (n == 0) {
  54.          // print solution
  55.          System.out.print(prefix+"\t");
  56.          theArray[c++] = prefix;
  57.       } else {
  58.          for (int i=0; i<n; i++) {
  59.             // recursive method call
  60.             displayString(prefix+s.charAt(i), s.substring(0, i)+s.substring(i+1, n));
  61.          }//for
  62.       }//if
  63.    }//displayString(String, String)
  64.  
  65.    public static int factorial(int n) {
  66.       return (n == 1)? 1: n * factorial(n - 1);
  67.    }//factorial()
  68. }//class Rearranger
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement