Java populate array randomly in matching game

72 views Asked by At

I have an array of 9 values. I want to populate another array of size 18 with those values randomly, with regards that they should occur only twice.

String[] cards = {"1","2","3","4","5","6","7","8","9"};
1

There are 1 answers

0
Gilbert Le Blanc On

Here's the result of my LazyRandomizer class.

[7, 5, 4, 7, 9, 3, 8, 1, 1, 3, 5, 4, 6, 2, 6, 2, 8, 9]

And here's the code.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class LazyRandomizer {

    public static void main(String[] args) {
        String[] cards = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };
        List<String> randomCards = new ArrayList<>();
        randomCards.addAll(Arrays.asList(cards));
        randomCards.addAll(Arrays.asList(cards));
        Collections.shuffle(randomCards);
        System.out.println(Arrays.toString(randomCards
                .toArray(new String[randomCards.size()])));
    }

}