How Can I get four random numbers from an array without getting the same one twice?

Hi, my character has to perform random tricks from a list of tricks. For this four random tricks need to be selected from the trick list.

How to do this is clear to me. However I want to avoid that he performs the same trick twice. How can I do this? I tried for each loop but just cant wrap my head around how to do this.

THX!

You can use the random range node to get a random number between indexes of the array. Just set to limit from 0 to the array length -1.

To be sure the consecutive numbers do not repeat with earlier ones:

Create array which will hold results.
In a for loop with break:

Compare the generated random number with result array (use contains check).

If the number does not exist in result array then add it, else select another random and repeat the check (do a loop back before the random range node)

Once you have the right amount in the return array you can call break on the random loop.

Return the result array.

Thx 3dRaven for the quick reply. Let me see if I am able to replicate what you suggested! thx again!

Random unique function:


Usage:

I wanted to make it a more universal function so it doesn’t just limit you to tricks.
Ideally it would be written with a wildcard array function but that requires c++ which not all people use in their projects.

Hope this helps.

2 Likes

Or just

:wink:

2 Likes

@ClockworkOcean Forgot about the shuffle node. Yes it’s more compact.
Work smarter not harder I guess :wink:

Edit: only downside is that shuffle seems to pass in the array by reference and will rearrange all items in it permanently.
Not sure if keeping order is crucial in this case. Perhaps shuffling a copy of the array would be a solution?

1 Like

Awesome guys!! I really appreciate your help! - ClockworkOcean; what value is the variable “N” in your example?

1 Like

The number of randoms you want :slight_smile:

I suggest the following solution:

Update 1:
Sorry I misread the question. Modified macro:

This is just a solution proposed by ClockworkOcean wrapped in a macro.

1 Like

This topic has been moved from International to Programming & Scripting.

When posting, please review the categories to ensure your topic is posted in the most relevant space.

Thanks and happy developing!

1 Like

I used this for my RNG Loot system in my RPG. This is fantastic thank you.

1 Like