Skip to content

Instantly share code, notes, and snippets.

@DanielJenkyn
Created October 16, 2019 18:11
Show Gist options
  • Save DanielJenkyn/e9212bfa959c440fd4ba2bb9677ffde1 to your computer and use it in GitHub Desktop.
Save DanielJenkyn/e9212bfa959c440fd4ba2bb9677ffde1 to your computer and use it in GitHub Desktop.
Permutations for given number
package com.and.test;
import java.util.ArrayList;
import java.util.List;
public class Solution {
/**
* Publicly exposed method, that wraps method with the actual algorithm.
* This is also to conform with the rules as outlined by the coding
* challenge - "NB Please do not change the name of the method or the way
* the functions is called"
*
* @param input The String to be permuted
* @return String containing permutations of input
*/
public static String solution(String input) throws NumberFormatException {
return solution("", input).toString();
}
/**
* Recursive algorithm for finding permutations of given string. Works by
* keeping one character fixed and then calculating permutations of the
* other characters.
*
* This method will produce duplicate permutations in the case that the
* input contains the same value twice - Eg 1123 will produce 2113 twice.
* Returns n! permutations
*
* @param prefix Stores result
* @param input The String to be permuted
* @return List containing permutations of input
*/
private static List<String> solution(String prefix, String input) {
List<String> permutations = new ArrayList<>();
if (input.isEmpty()) {
permutations.add(prefix);
} else {
for (int i = 0; i < input.length(); i++) {
permutations.addAll(solution(prefix + input.charAt(i), input.substring(0, i) + input.substring(i + 1)));
}
}
return permutations;
}
/**
* sanitizeString will sanitize; in this case meaning removing all non-digit
* characters for the given input.
*
* \D - matching all non-digits
*
* @param input The String to be sanitized
* @return The resulting string
*/
private static String sanitizeString(String input) {
return input.replaceAll("\\D", "");
}
public static void main(String args[]) {
/**
* Just a quick way to generate a random string,
* Requires import java.util.UUID;
* String input = UUID.randomUUID().toString().substring(4,8);
*/
String input = "1234";
input = sanitizeString(input);
System.out.println(solution(input));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment