Created
December 11, 2019 10:34
-
-
Save atamrawi/4dbc098c12efd5735829d08fea591985 to your computer and use it in GitHub Desktop.
SWEN 6301 - Assignment 4 - Problem 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class StringPermutator { | |
public static void permutate(String string) { | |
int [] factorials = new int[string.length()+1]; | |
factorials[0] = 1; | |
for (int i = 1; i<=string.length();i++) { | |
factorials[i] = factorials[i-1] * i; | |
} | |
for (int i = 0; i < factorials[string.length()]; i++) { | |
String onePermutation=""; | |
String temp = string; | |
int positionCode = i; | |
for (int position = string.length(); position > 0 ;position--){ | |
int selected = positionCode / factorials[position-1]; | |
onePermutation += temp.charAt(selected); | |
positionCode = positionCode % factorials[position-1]; | |
temp = temp.substring(0,selected) + temp.substring(selected+1); | |
} | |
System.out.println(onePermutation); | |
} | |
} | |
public static void main(String[] args) { | |
System.out.print("Enter string to permutate: "); | |
Scanner scanner = new Scanner(System.in); | |
String string = scanner.nextLine(); | |
scanner.close(); | |
permutate(string); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code is adopted from https://stackoverflow.com/a/11471673. It performs iterative approach to string permutations.