-2

I am a high-school student, relatively new to programming, and am working on a mathematics problem and using java to help me. Anyway, I have run into a problem with memory. I would like to find all the possible combinations of a string without repeats.

For example, given the string 'AABB' I would want 'AABB', 'ABAB', 'ABBA', 'BBAA', 'BABA', and 'BAAB' returned.

There is a similar question asked here: Every combination of character array

The solution provided at this link is in general what I want, however in my case it is unable to handle longer strings. In my specific case I want a method that is able to take a string with 18 characters in it.

Additionally the string which I would like to find all the combinations of, only needs to contain 2 characters; and so, there may be a more efficient way to do it in binary, but I am not sure.

Any help would be greatly appreciated.

Community
  • 1
  • 1

2 Answers2

0

The set of distinct strings of length 18 made up of 2 characters is 2^18 or 262,144 in number.

Pseudo code:

  1. Create the set (262,144) of all possible strings of length 18 made up of 2 distinct characters
  2. Determine the number of characters of type A in the input string
  3. Determine which strings in the set have equal number of characters of type A as the input string
  4. Print out these strings
Stephen Donecker
  • 2,361
  • 18
  • 8
0
 static void perm(char c0, int n0, char c1, int n1, String s, List<String> result) {
     if (n0 < 0 || n1 < 0)
         return;
     else if (n0 == 0 && n1 == 0)
         result.add(s);
     else {
         perm(c0, n0 - 1, c1, n1, s + c0, result);
         perm(c0, n0, c1, n1 - 1, s + c1, result);
     }

 }

 static List<String> perm(char c0, int n0, char c1, int n1) {
     List<String> result = new ArrayList<>();
     perm(c0, n0, c1, n1, "", result);
     return result;
 }

 public static void main(String[] args) {
     System.out.println(perm('A', 2, 'B', 2));
     // -> [AABB, ABAB, ABBA, BAAB, BABA, BBAA]
     System.out.println(perm('A', 8, 'B', 10).size());
     // -> 43758
 }
  • It's probably better to use a LinkedList than an ArrayList to prevent unnecessary resizing. Appending to a LinkedList is always O(1). – Kevin Ji Jul 03 '15 at 23:24
  • Thank you so much. This is very helpful to me. I thot the code for this was going to have to be more complex than this (but luckily it does not.) I was very happy when this ran all the way thru in a reasonable amount of time, and I was able to see a list of all the different combinations! – Tristan Phillips Jul 03 '15 at 23:53