Skip to content

Instantly share code, notes, and snippets.

@atamrawi
Created December 11, 2019 10:34
Show Gist options
  • Save atamrawi/4dbc098c12efd5735829d08fea591985 to your computer and use it in GitHub Desktop.
Save atamrawi/4dbc098c12efd5735829d08fea591985 to your computer and use it in GitHub Desktop.
SWEN 6301 - Assignment 4 - Problem 1
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);
}
}
@atamrawi
Copy link
Author

This code is adopted from https://stackoverflow.com/a/11471673. It performs iterative approach to string permutations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment