Generate random strings with specified characters?

Well, I got stuck on how to generate strings with all possible values with the specified characters. Okay, I don't know how to explain it well, so here is an example:

chars: a, b, c

generation:

abc
aab
abb
acc
baa
bbb
bbc
bac
cab
ccc
aaa
cbb
caa
ccb
cca
bab
bcb

I've tried using a character list, and then iterating every character in this list, and then iterate again every character on the list, but... let's say it doesn't worked.

Upvotes: 0

Views: 553

Answers (2)

Andre Yonadam
Andre Yonadam

Reputation: 1034

I quickly made this code below. You might have to edit it a bit for it to work or adapt to your needs I just wanted to share the idea of my code with you. However I would recommend jlordo's answer because its more efficient.

Array String[] = new Array[]{"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"}
ArrayList<String> numbersrandom;
for(int a = 0; i <= 26; i++){
for(int b = 0; i <= 26; i++){
for(int c = 0; i <= 26; i++){
numbersrandom.add(String[a]+String[b]+String[c]);
}
}
}

After using this code, you can use a random generator and for loop to randomly mix these. Good Luck!

Upvotes: 1

jlordo
jlordo

Reputation: 37843

A copy from my own answer on this question:

This will work for a,b,c or any other continuous sequence of characters:

import java.util.Arrays;
import java.util.Iterator;

public class BruteForceIterator implements Iterator<String> {

    private char min, max;

    private char[] current;

    private char[] last;

    private int reachedLast = 0;

    public BruteForceIterator(char min, char max, int length) {
        this.min = min;
        this.max = max;
        current = new char[length];
        Arrays.fill(current, min);
        last = new char[length];
        Arrays.fill(last, max);
    }

    @Override
    public boolean hasNext() {
        return reachedLast < 2;
    }

    @Override
    public String next() {
        String str = new String(current);
        for(int i = current.length - 1; i >= 0; i--) {
            char next = following(current[i]);
            current[i] = next;
            if (next != min) {
                break;
            }
        }
        if (Arrays.equals(current, last) || reachedLast > 0) {
            reachedLast++;
        }
        return str;
    }

    private char following(char in) {
        if (in < max) {
            return (char) (in + 1);
        } else {
            return min;
        }
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException("No with me, sir!");
    }

    public static void main(String[] args) {
        BruteForceIterator bit = new BruteForceIterator('a', 'c', 3);
        while (bit.hasNext()) {
            System.out.println(bit.next());
        }
    }
} 

Upvotes: 3

Related Questions