To find the combinations of a string, either the logic needs to use for loop or recursive loop.
As for loop depends on the string length, for each loop we have to write the logic again, as more swapping will happen when try to get the combinations.
Since swapping will happen recursively based on the positions of the input string, recursive function will be the best choice for finding all combinations of a String.
For Input: ABC
Output:
ABC
ACB
BAC
BCA
CAB
CBA
The above output is 2 Power n, where n is the length of the string.
The recursive logic is swapping each of the character to a different position., and continuing swapping until get all combinations.
For Input: ABC
Steps:
- Take A as index characters, and do the Swap between B & C.
- ABC, BAC, CAB
- Since the first character is done, call the same method again and pass the remaining string(others) resulted from for loop.,
- Once the values are fetched, keep first character untouched and call the same method again.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.tutorialflow.combinations; public class Main { public static void main(String[] args) { String input = "ABC"; combinationOfString(input, "", input.length()); } private static void combinationOfString(String input, String others, int length) { if(others.length() == length) { System.out.println((others + input)); } for(int i=0;i < input.length();i++) { String sel = input.charAt(i)+""; String remprev = input.substring(0,i); String remnext = input.substring(i+1, input.length()); combinationOfString(remprev+remnext, others+sel, length); } } } |
Output:
ABC
ACB
BAC
BCA
CAB
CBA