jeudi 8 décembre 2016

Generating specific random string arrays

I know, the title seems a bit odd, let me explain.

I want to generate random string arrays which must be made up of specific given elements.

Let's say these elements are: Bread, Milk, Cereal and Coffee.

The Java code should pick randomly one of those and put it in the arrays.

I made some progress and managed to produce, as an example, 10 arrays with the following code:

    String[] elements = new String[] {"Bread","Milk","Cereal","Coffee"};

    for (int i=0; i < 10; i++) {

        int random_number = ThreadLocalRandom.current().nextInt(2, 5);

        String[] list = new String[random_number];

        System.out.print("[");

        for (int j=0; j < random_number; j++) {

            int pos = ThreadLocalRandom.current().nextInt(0, 4);
            list[j] = elements[pos];
            System.out.print(list[j]+ ", ");
        }

        System.out.println("]");
        }

One possible output looks like this:

[Coffee, Coffee, Coffee, Bread, ]
[Bread, Bread, Coffee, ]
[Coffee, Coffee, Cereal, ]
[Milk, Cereal, ]
[Cereal, Coffee, ]
[Coffee, Cereal, Bread, ]
[Cereal, Cereal, Milk, Milk, ]
[Milk, Bread, Milk, ]
[Bread, Coffee, ]
[Coffee, Bread, ]

There are two problems.

First is not very important, but would be nice not having the , after the last element of each array.

The second issue which is the main one is: I do not want duplicate elements inside each array.

Bread, Milk, Cereal, Coffee must no show more than once in each array.

So, for example, [Coffee, Coffee, Coffee, Bread] is wrong.

In other words, one possible correct output would be:

[Bread, Milk]
[Bread, Milk, Cereal, Coffee]
[Bread, Cereal, Coffee]
[Bread, Cereal]
[Bread, Coffee]
[Milk, Coffee]
[Milk, Cereal]
[Milk, Cereal, Coffee]
[Cereal, Coffee]

It's fine if two or more of the arrays are identical.

Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire