How to get random items from array, no duplicates, and specific number of them

I am trying to generate an array of Names.

The names are retrieved from a database where they are sorted by enumerators, seen here:

How many Names to put into the new array? That depends on a Map, where key = Enum / value = int, seen here:
image

So for example, the map might tell us that from group A we should grab 2 names, and from group B we grab 4 names.

There should be no duplicate names.

What I have done is get the keys of the map (the enumerator which determines the “group”), and For Each group, find the map value (the int which determine show many names to select).

That int determines the length of a ForLoop, which is used to get random names from the Group:

Now, the problem occurs when I want to check for duplicates. If there is a duplicate, I should discard it and run the loop again. But how do I control the iteration of the for loop indexes?

I can think of a few “hacky” ways, like just chopping the array to length after the for loop, but there is probably a way I can be more explicit to just get the desired numbers?

Any advice is appreciated!

Let’s say you need random 3 names from Array 1.
What you can do is create new empty array (so you don’t mess up your original one), add all elements from Array 1 in to it. Do a shuffle of your new array (this will randomize it, and keep original as it is). And take first three names from new array.

This will give you three random non duplicated names from the Array 1 you have provided.

2 Likes

Tested and it works - very simple too. Thanks a lot.

here is my code (edited for an error):

overall side left


overall side right

shuffle each group

grab a name from associated group, using the for loops index

result: