HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Calculate all possible combinations of given characters

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
combinationsallpossiblecalculatecharactersgiven

Problem

I was asked in my textbook Lectures on Discrete Mathematics for Computer Science to construct a program that would take an alphabet ({a,b,c} or any combination of characters {1,4,s,a}) as well as a length value and calculate all possible combinations of this alphabet.

For example:

char[] alphabet = new char[] {'a','b'};
possibleStrings(3, alphabet,"");


This will output:

aaa
aab
aba
abb
baa
bab
bba
bbb


That is all combinations of the alphabet {a,b,c} with the string length set to 3.

The code I have written is functional, however I'd like to read what things I am doing wrong or could be doing better. The book didn't give an example program, so I only hope this is what it was looking for, but maybe there's a much better way to do it or way to improve how I'm doing it. Maybe this is fine, but I just need someone to look at it and tell me in that case.

public class Program {

    public static void main(String[] args) {

        // Create an alphabet to work with
        char[] alphabet = new char[] {'a','b'};
        // Find all possible combinations of this alphabet in the string size of 3
        StringExcersise.possibleStrings(3, alphabet,"");
    }

} class StringExcersise {

    public static void possibleStrings(int maxLength, char[] alphabet, String curr) {

        // If the current string has reached it's maximum length
        if(curr.length() == maxLength) {
            System.out.println(curr);

        // Else add each letter from the alphabet to new strings and process these new strings again
        } else {
            for(int i = 0; i < alphabet.length; i++) {
                String oldCurr = curr;
                curr += alphabet[i];
                possibleStrings(maxLength,alphabet,curr);
                curr = oldCurr;
            }
        }
    }
}

Solution

your code looks fine.

  • a slight performance improvement i'd do is pass a StringBuilder instead of a String - a String in java is immutable so every time you call curr += alphabet[i] youre actually allocating a new String object. instead you could append the character to a StringBuilder (and delete the last character when you leave) to save on the number of Objects created during the run



  • `for(int i = 0; i

Context

StackExchange Code Review Q#41510, answer score: 4

Revisions (0)

No revisions yet.