# Random Array Routine



## polypx (Aug 6, 2010)

This is a question that I'm sure will be very obvious for anyone with "real" programming experience.

How do I fill an array with random numbers, without using the same number twice?

ie. Let's say it's [0, 1, 2, 3, 4] and I want to randomize them, but without repeats.

I can't just random(0, 4) for each index, since that might result in a repeat. I need to guarantee that all numbers are there once, but in a random order.

I'm sure this is programming 101, but any advice much appreciated.

cheers
Dan


----------



## kotori (Aug 6, 2010)

I wrote you an implementation of Fisher–Yates shuffle. Here you are:

*function* swap(a, b)
``*declare* tmp
``tmp := a
``a := b
``b := tmp
*end function*

*function* shuffle(x)```_{ Fisher–Yates shuffle }_
``*declare* i
``*declare* j
``*for* i := num_elements(x)-1 *downto* 1
````j := random(0, i)
````swap(x[ i], x[ j])
``*end for*
*end function*

_{ sample usage: }_
*on init*
``*declare* list[5] := (0, 1, 2, 3, 4)
``shuffle(list)
``message(list[0] & list[1] & list[2] & list[3] & list[4])``
*end on*

Cheers,
Nils


----------



## polypx (Aug 7, 2010)

Thanks again Nils. It works fabulously, and is SO useful.

cheers
Dab


----------

