1

I have the following code that prints the total possible combinations of a given length of a string of numbers.

However, if I wanted to remove all the numbers with leading zeroes (i.e. 001, 002, 003) from this count, what could I do? I thought about using indexOf(), but I can't figure out how to implement it when I don't have specific set values. Any thoughts? Thank you!

public class Combinations {
public static void main(String[] args) {
    printAllPossibilities("012345", 3);
    System.out.println("Combinations: " + counter);
}

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));
}

}

  • 2
    `"012345".replaceAll("^0*", "");` ? - https://stackoverflow.com/questions/2800739/how-to-remove-leading-zeros-from-alphanumeric-text – Scary Wombat Sep 09 '21 at 02:32
  • Hi! Thanks for your answer. I don't think that factors into the total combinations counted, though: I want to remove all combinations with leading zeroes from my final total. – learningjava Sep 09 '21 at 02:36
  • 1
    Simply modify your `printAllPossibilities_` method to return before increasing the count or printing the number if it starts with a zero. `if(yourString.startsWith("0"))...` – sorifiend Sep 09 '21 at 02:41

1 Answers1

0

Sounds like all you need to do is add an extra validation in the base condition to check if the number starts with 0 or not.

Update to:

static void printAllPossibilities_(String charSet, int length, String temp) {
    if (length == 0) {

        // increment counter ONLY if there are no leading zeroes.
        if (temp.charAt(0) != '0') {
            System.out.println(temp);
            counter += 1;
        }

        return;
    }

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

Remember to also validate that the temp string is neither NULL nor empty string ""(size 0) before calling charAt(0), otherwise you could receive a NullPointerException or IndexOutOfBoundsException at runtime.

AlexMelgar
  • 86
  • 5