2

I´m looking for a algorithm which returns me a list of all possible combinations of x-characters and a defined length.

For example when I have the characters a and b and the length two I would like to get this output:

a
b
aa
ab
ba
bb

But I also want the code to be resumable, so that I can save the current combination/position and resume at exactly the same combination/position.

This was my first try, it works fine but it is not resumable or at least I have no idea how to do it:

public class test {
    static char[] chars = "ab".toCharArray();
    static int maxLength = 2;

    public static void main(String[] args) {
        nextString("");
    }

    private static void nextString(String s) {
        int i = 0;
        while (i < chars.length) {
            String snew;
            snew = s + new Character(chars[i]).toString();
            System.out.println(snew);
            if (snew.length() <= maxLength - 1)
                nextString(snew);

            i++;
        }
    }

}
Ka Rl
  • 517
  • 8
  • 15
  • 5
    Show your work - where are you stuck? Don't post problems and expect solutions. – torquestomp Mar 15 '14 at 22:29
  • How far have you got so far? – Mark Butler Mar 15 '14 at 22:31
  • If we take aside the requirement to be resumable, this is one of the most standard recursive algorithms. So you can just search for `recursion` and `permutation` and a lot of solutions will comes up. Also, I know this problem as `Vector 0/1` so you can try search for this too. – Leron Mar 15 '14 at 22:35
  • The first two results do not have the same length as the others. You could add the empty string `""` to the input, but then the empty string would also be part of the output. You may want to have a look at https://github.com/javagl/Combinatorics/blob/master/src/main/java/de/javagl/utils/math/combinatorics/CombinationIterable.java – Marco13 Mar 15 '14 at 22:40
  • Generate the combinations and store it an array? That way you can use the array index or combination string lengths for storing and resuming. – chettyharish Mar 15 '14 at 22:46
  • I could post a code which works like the other hundreds which are out there but this wouldn't help. Generating all combinations is not the problem. The problem is, if you do it recursively, it is very hard to resume. – Ka Rl Mar 16 '14 at 00:26
  • As it is on hold, gonna answer it here. Why don't you try to make some code to, given a combination, yield the next. Like next_combination(['a', 'b'], 'aab') == 'aba'? This way, you could call value = next_combination(value) successively, stop any time and resume when you wish. – Juan Lopes Mar 16 '14 at 04:27
  • I added my code, I hope this helps. The code works fine but I dont know how I could resume at a specific position. – Ka Rl Mar 16 '14 at 19:59

0 Answers0