javaalgorithm

Generate all possible string from a given length


I would like to be able to generate all possible strings of a given length, and I frankly don't know how to code that. For further explanation, a friend and I would like to demonstrate some basic hacking techniques, so brute forcing comes up. Of course, he will be my victim—no illegal activity here.

The only thing he told me is that his password will be 4 characters long, but I'm pretty sure his password won't be in any dictionary; that would be too easy.

So I came up with the idea of generating every possible 4-character-long string, containing only a-z characters (no caps).

Would someone have a lead on how to code such an algorithm? I don't really mind performance; if it takes one night to generate all passwords, that's no problem.

Don't forget, this is purely for demonstration purposes.


Solution

  • You can do it just how you'd do it with numbers. Start with aaaa. Then increment the 'least significant' part, so aaab. Keep going until you get to aaaz. Then increment to aaba. Repeat until you get to zzzz.

    So all you need to do is implement is

    String getNext(String current)
    

    To expand on this; It possibly isnt the quickest way of doing things, but it is the simplest to get right.

    As the old adage goes - 'first make it right, then make it fast'. Getting a working implementation that passes all your tests (you do have tests, right?) is what you do first. You then rewrite it to make it fast, using your tests as reassurance you're not breaking the core functionality.