my code takes a string like "abc" and combines the letters in the string in all possible combinations, for example
"ab" returns
"aa, ab, ba, bb, aaa, aab, aba, abb, baa, bab, bba, bbb"
I can also modify it’s length.
My problem here is that I only want to use each letter once if I only have 1 of said letter, for example if I only have 1 letter "a" I only want my program to use 1 letter "a", but if I have two letters "a" for example "aa" I do want it to use both of those As on all positions.
Here’s the code:
public class Words { static char[] alphabet = "ab".toCharArray(); static void generate(StringBuilder sb, int n) { if (n == sb.length()) { System.out.println(sb.toString()); return; } for (char letter : alphabet) { sb.setCharAt(n, letter); generate(sb, n + 1); } } public static void main(String[] args) { StringBuilder sb = new StringBuilder(); for (int length = 2; length <= 3; length++) { sb.setLength(length); generate(sb, 0); } } }
Anonymous Asked question May 14, 2021
Recent Comments