V-ed
V-ed

Reputation: 3

Randomizing an array of string without repetitions

So I'm confronted to a little problem: I want to randomize an Array of Strings without any repetitions. I've already searched for such thing AND I found some "Randomising an Array without Repetitions" but all I can find is about randomising an array of int and it doesn't give me the results I want.

Here's my code (that i shortened just a bit to show only the useful part) so you guys can help me with the use of my own code. The array I want to randomise is the allCommands[] one. Anyway, here it is:

 Box box = Box.createVerticalBox();

        String[] allCommands = new String[]{"start", "help", "hint", "look around", "take note",
                "look under bed"};

        JLabel[] fun = new JLabel[allCommands.length];

        for(int o = 0 ; o < allCommands.length ; o++){

            fun[o] = new JLabel(allCommands[o]);

            box.add(fun[o]);

        }

Quick note: The allCommands[] array in my codes is way larger and I might get it even bigger, so I thought about a way to make the randomiser easily expandable...
I tried things like Collection and ArrayList (or something like that) and I didn't found the result I wanted.

Quick note #2: If my questions isn't very clear or you want me to add more detail about variables in my codes or something else, just tell me and I'll edit this out.

Quick note #3 (so many quick notes!): I'm kinda new to programmation. In a result, I would prefer using for() loops, Arrays, if() and else if if possible. But any way of doing a randomisation without repetitions for an array of Strings will make me happy...

All of my thanks!

Upvotes: 0

Views: 226

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201399

If you want to shuffle your array allCommands there are several ways you could. Here is one using Collections.shuffle() and Arrays.asList() to shuffle a List backed by allCommands, -

String[] allCommands = new String[] { "start",
    "help", "hint", "look around", "take note",
    "look under bed" };
System.out.println(Arrays.toString(allCommands));
Collections.shuffle(Arrays.asList(allCommands)); // <-- shuffles allCommands
System.out.println(Arrays.toString(allCommands));

Upvotes: 1

Related Questions