learningjava
learningjava

Reputation: 49

How to count combinations in recursive function?

So, I have this block of code that takes something like printAllPossibilities("1234", 2) and prints all combinations of the string of length 2.

I want it to be able to find all possible combinations (for another part I'll be adding later) AND count the total number of combinations found. I tried adding a counter in the for loop, but it doesn't seem to be working in the way I applied it. Any thoughts are appreciated!

static void printAllPossibilities(String charSet, int length) {
  printAllPossibilities_(charSet, length, "");
}

static void printAllPossibilities_(String charSet, int length, String temp) {
  if (length == 0) {
    System.out.println(temp);
    return;
  }
  for (int i = 0; i < charSet.length(); i++)
    printAllPossibilities_(charSet, length - 1, temp + charSet.charAt(i));
}

Upvotes: 1

Views: 201

Answers (2)

vszholobov
vszholobov

Reputation: 2363

You can count number of combinations this way

static void printAllPossibilities(String charSet, int length) {
    int cnt = printAllPossibilities_(charSet, length, "");
    System.out.println(cnt);
}

static int printAllPossibilities_(String charSet, int length, String temp) {
    if (length == 0) {
        System.out.println(temp);
        return 1;
    }
    
    int res = 0;
    for (int i = 0; i < charSet.length(); i++) {
        res += printAllPossibilities_(charSet, length - 1, temp + charSet.charAt(i));
    }

    return res;
}

Also you could use Permutations with Repetition formula

static void printAllPossibilities(String charSet, int length) {
    printAllPossibilities_(charSet, length, "");
    int cnt = (int) Math.pow(charSet.length(), length);
    System.out.println();
    System.out.println(cnt);
}

Upvotes: 2

Jonny Henly
Jonny Henly

Reputation: 4233

If I understand your code correctly, you can do the following:

static void printAllPossibilities(String charSet, int length) {
  printAllPossibilities_(charSet, length, "");
}

// declare counter
static int counter = 0;

static void printAllPossibilities_(String charSet, int length, String temp) {
  if (length == 0) {
    System.out.println(temp);

    // increment counter
    counter += 1;

    return;
  }
  for (int i = 0; i < charSet.length(); i++)
    printAllPossibilities_(charSet, length - 1, temp + charSet.charAt(i));
}

Then output counter when you see fit.

Upvotes: 2

Related Questions