Skip to content

Non repeating character from a preset of characters

I would like to pick a random letter out of a list B, C, D at random order and would make sure that they do not repeat. I have tried this but it repeats the letters

public class Test {
    static Random r = new Random();    
    static char pickRandom(char... letters) {
        return letters[r.nextInt(letters.length)];
    }
    public static void main(String args[]) {
        for (int i = 0; i < 10; i++) {
            System.out.print(pickRandom('B', 'C', 'D'));
        }
    }
}

Answer

You should check, if character already taken, for example declare another one array which contains already taken character, so if character caontains in this array, try to select another character, OR you can simply use Collections.shuffle method(Collection knowledge required)

List<Character> solution = new ArrayList<>();
solution.add('a');
solution.add('Y');
solution.add('Z');
Collections.shuffle(solution);