Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java increment string through array

Tags:

java

I don't know why I can't work this one in my head.

I have an array of characters in my Java code..

private String[] letters = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
};

What I need to do is loop through building strings for every possible configuration.

Example:

a aa ab ac . . . aaa aab aac . . . . aba abc

and so on up to n length.

Can any one point me in the direction with this problem.

Cheers

like image 534
jlabroy Avatar asked Apr 08 '26 15:04

jlabroy


1 Answers

Yet another recursive approach. I'm working in the other direction from @liwp. There's a slight advantage that I only allocate one output ArrayList. Also, for simplicity, I just put in the numbers 0...9 in this example

static public void combos(String[] inputs, List<String> outputs, String preface, int maxDepth) {
        if (preface.length() >= maxDepth)
           return;
        for (String s : inputs) {
           // swap the order of these two lines if you want depth first
           outputs.add(preface+s);
           combos(inputs, outputs, preface+s, maxDepth);
        }       
     }


     public static void main(String[] args) {
        String[] numbers = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        ArrayList<String> outputs = new ArrayList<String>();
        combos(numbers, outputs, "", 3);
        System.out.println(outputs);

     }

will print out

[0, 00, 000, 001, 002, 003, 004, 005, 006, 007, 008, 009, 01, 010, 011...
like image 189
user949300 Avatar answered Apr 11 '26 03:04

user949300