0

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.

1
  • Use a Set<> to add elements. and Random#nextInt(int) to generate random index to get random values Commented Dec 8, 2016 at 12:39

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;
    }
}

7 Comments

Yes, I need variable number of elements. The second code works almost fine, but it seems that if I add a fifth element (let's say "Sugar") I get lists made up by 1 element, lists made up by 2 elements and lists made up by 3 elements. Oddly, there are no lists with 4 elements, not even one! If I add a sixth element (let's say "Salt"), it does not produces neither lists with 4 elements nor lists with 5 elements, Another minor thing: is it possible to remove "Array 0 =" , "Array 1" and so on resulting in getting just the lists? Thanks a lot.
I've edited the reply to print just the arrays. Have to check again with the issue about element number.
Well, actually I can't confirm true what you say about the array element numbers. I get all combinations up to the size of elements. However the quality of random number we get using ThreadLocalRandom.current().nextInt(0, elements.length) is questionable, it might happen that you simply didn't get random number above 4. Try changing 15 in main() method to 100 and see if you get more variety.
That's truly weird! With 6 different item, I also tried going for 200 arrays but I can't get a single 4 or 5 item array in the output! Could it be related to the specifc jre version maybe on how the ThreadLocalRandom works?!
Could you show your full code? Maybe using pastebin or similar service.
|
0

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);
}

Comments

0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.