public class Main {
// Given a string of alphabets and a number k, write a function to print all of the combinations of length k of these alphabets.
// The string does not contain duplicate alphabets.
// EXPECTED OUTPUT: abd, abs, abe, ads, ade, ase, bds, bde, bse, dse.
public static void main(String[] args) {
char[] alphabet = { 'a', 'b', 'd', 's', 'e' };
int k = 3; // length of output string.
System.out.println("EXPECTED OUTPUT: abd, abs, abe, ads, ade, ase, bds, bde, bse, dse");
System.out.print("ACTUAL OUTPUT: ");
printAllCombinations(alphabet, k);
}
// Base function used to call the recursive version of itself with given alphabet and length, k.
private static void printAllCombinations(char[] alphabet, int k) {
// Initially set the prefix to "" and n to 0, while passing alphabet and length, k to printAllCombinations.
printAllCombinations(alphabet, "", 0, k);
}
// Recursive method used to print all possible strings of length k, given a set of characters.
// However, use n to keep track of your current location in the array alphabets.
private static void printAllCombinations(char[] alphabet, String prefix, int n, int k) {
// Base case: k is 0,
// print prefix.
if (k == 0) {
// Only print ', ' if n is less than the length of the current prefix.
if (n > prefix.length()) {
System.out.print(", ");
}
System.out.print(prefix);
return;
}
// One by one add all characters
// from set and recursively
// call for k equals to k - 1.
// However, loop only from n to length of the alphabet.
for (int i = n; i < alphabet.length; i++) {
// Next character of input added.
String newPrefix = prefix + alphabet[i];
// k is decreased and n is increased, because
// we have added a new character.
printAllCombinations(alphabet, newPrefix, i + 1, k - 1);
}
}
}
Comments