NoobNe0
NoobNe0

Reputation: 385

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.

Upvotes: 0

Views: 161

Answers (4)

secretwpn
secretwpn

Reputation: 71

This would be one approach if you don't care too much about efficiency

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

public class RandomArrays {
    public static void main(String[] args) {
        String[] elements = new String[]{"Bread", "Milk", "Cereal", "Coffee"};
        for (int i = 0; i < 15; i++) {
            final String[] array = generateRandomArrayFromElements(elements);
            System.out.println(Arrays.toString(array));
        }
    }

    private static String[] generateRandomArrayFromElements(String[] elements) {
        final List<String> list = Arrays.asList(elements);
        Collections.shuffle(list);
        return list.toArray(new String[list.size()]);
    }
}

Or if you need variable number of elements you can do this:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;

public class RandomArrays {
    public static void main(String[] args) {
        String[] elements = new String[]{"Bread", "Milk", "Cereal", "Coffee"};
        for (int i = 0; i < 15; i++) {
            final String[] array = generateRandomArrayFromElements(elements);
            System.out.println(Arrays.toString(array));
        }
    }

    private static String[] generateRandomArrayFromElements(String[] elements) {
        int size = ThreadLocalRandom.current().nextInt(0, elements.length) + 1;
        String[] array = new String[size];
        ArrayList<Integer> usedIndices = new ArrayList<>(size);
        for (int i = 0; i < array.length; i++) {
            int randomIndex = getUniqueRandomIndex(usedIndices, size);
            usedIndices.add(randomIndex);
            array[i] = elements[randomIndex];
        }
        return array;
    }

    private static int getUniqueRandomIndex(ArrayList<Integer> usedIndices, int max) {
        int randomIndex = ThreadLocalRandom.current().nextInt(0, max);
        final boolean contains = usedIndices.contains(randomIndex);
        if (contains)
            randomIndex = getUniqueRandomIndex(usedIndices, max);
        return randomIndex;
    }
}

Upvotes: 0

J-J
J-J

Reputation: 5871

First of all there will not be a , in array, the , comes from the System.out.print(list[j]+ ", ");, it has nothing to do with arrays.

To avoid the duplicates replace the String array String[] list = new String[random_number]; with a Set, Set<String> set = new HashSet();

Upvotes: 0

Gurwinder Singh
Gurwinder Singh

Reputation: 39457

You can use Set and Random like so:

String[] elements = new String[] {"Bread","Milk","Cereal","Coffee"};
Random r = new Random();
for(int i=0;i<10;i++)
    Set<String> set = new HashSet<>();
    for (int j=0; j < 4; j++) {
       set.add(elements[r.nextInt(4)]);
    }
    System.out.println(set);
}

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691625

Create a list containing your 4 elements. Shuffle it. Pick a random int between 0 and 4. Take the sublist starting at 0 and ending at this random index. Print the list. Repeat as many times you want.

Upvotes: 2

Related Questions