How to get a random element from an array thats different from previous one?

guys I’ve an array of actors which im getting a random element every 20 seconds to do some stuff. The problem i have is that sometimes the random element is equal to the current element that is being used, and i don’t want that. So my question is how do i get an element that’s different from the previous element?

There are many ways to do this. The easiest is to remember which item was returned the last time, and check the next item picked against that, and if it’s the same, simply pick again, in a loop.
As long as there is more than one item to pick from, this loop will always finish quickly because of properties of pseudo-random generators – there is actually no risk of an infinite loop.

thats what i did in the first place. but the loop doesn’t keep up and site only gets called once


it throws me an error saying its an infinite loop.

1 Like

Remove the element from the array once it’s been used.

1 Like

no, i want to use the same element later on, its just sometimes the same element is being used twice at the same time.

Nothing stops you from repopulating the array later on. Keep a temporary array, pick an element, remove it. You can still hold onto the original array, ofc.


Alternatively, have an array → shuffle → use Last Index → move the Last Index to 0. Rinse & repeat. Other elements must move, too. But removing is easier / more efficient and not prone to indexing error.


Also, your Shuffle does nothing in the pic.

what u mean shuffle node does nothing its actually giving me a random element lol.

nvmi figured it out myself. just needed a delay node before calling it again.

You could just use a while loop and generate a random int. You are already doing that but with more unnecesary steps.

There is a get random array item node.

Except that one doesn’t make sure the next item is not the same as the previous item, which was the main thrust of this question.

2 Likes

to get random items that don’t repeat. what i do is:

  • at the start shuffle the array
  • every time i need a new item, i have an index counter that increments by one, and pick that item.
  • when reaching the end of the list, re-shuffle.

there’s a simple way to shuffle an array in place, something like
(pseudocode)


last = Array.num()-1
for i in 0 to last:
     r = GetRandomInRange(i, last)
     swapped = Array[i]
     Array[i] = Array[r]
     Array[r] = swapped

You can achieve this by storing the previous element and using a simple loop to keep picking a new random element until it’s different.