Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package StringPerm;
- import java.util.ArrayList;
- /*
- * Name: George Colon
- * Date: 11/20/2017
- * Course Number: CSC 111
- * Course Name: Data structures
- * Email: Gcolon6085@student.stcc.edu
- */
- import java.util.Scanner;
- public class StringPermHomeWork {
- //**********************************************
- private static void process(Scanner sc, String args[]) {
- // Code here is merely a sample
- String x;
- System.out.print("Please enter a string: ");
- x = sc.next();
- sc.nextLine(); // IMPORTANT!! Reset Scanner
- System.out.println("Processing " + x + " ...");
- displayPermutation(x);
- }
- //**********************************************
- private static boolean doThisAgain(Scanner sc, String prompt) {
- System.out.print(prompt);
- String doOver = sc.nextLine();
- return doOver.equalsIgnoreCase("Y");
- }
- //**********************************************
- public static void main(String args[]) {
- final String TITLE = "CSC111 String Permutation";
- final String CONTINUE_PROMPT = "Do this again? [y/N] ";
- System.out.println("Welcome to " + TITLE);
- Scanner sc = new Scanner(System.in);
- do {
- process(sc, args);
- } while (doThisAgain(sc, CONTINUE_PROMPT));
- sc.close();
- System.out.println("Thank you for using " + TITLE);
- }
- public static void displayPermutation(String s) {
- // using this array list to keep track of already printed outputs.
- // If the char has matching characters this e.g. aaabbc without it we will get
- // outputs multiple times
- // The math of this is 6! / 3!*2! this will give 60 outputs yet without the
- // array list we would have 720.
- ArrayList<String> used = new ArrayList<String>();
- worker("", s, used);
- }
- public static void worker(String s1, String s2, ArrayList<String> used) {
- if (s2.length() == 0 && used.contains(s1) == false) {
- used.add(s1);
- System.out.println(s1);
- } else {
- StringBuilder string = new StringBuilder(s2);
- StringBuilder hold = new StringBuilder(s1);
- for (int i = 0; i < string.length(); i++) {
- char h = string.charAt(i);
- // Move down a level -Recursively solve-
- worker(hold.append(h).toString(), string.deleteCharAt(i).toString(), used);
- // add the removed back in the order they were removed
- string.insert(i, h);
- hold.deleteCharAt(hold.length() - 1);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement