Go Down

### Topic: How to randomize 4 digits in an array? (Read 679 times)previous topic - next topic

#### zondernaam

##### Jan 24, 2013, 10:38 am
Hi, I've searched through the forums and can't seem to find an open topic about randomizing the numbers in an array.

I have an array with 4 cells and I need to randomize the numbers 0-3 without duplicating any of them.

I'm fairly new to programming, but this seems like something that could be resolved with simple logic..unbeknownst to me.

i.e. - int myArray [4] = {random # 0-3, random # 0-3, random # 0-3, random # 0-3};
...where each number wouldn't duplicate any of the others.

Sorry if that formatting is confusing, and thank you for your help.

#1
##### Jan 24, 2013, 10:41 am

"Shuffle" is the keyword...

#### zondernaam

#2
##### Jan 24, 2013, 10:42 am
Thank you for the speedy response, I'll give it a look.

#### zondernaam

#3
##### Jan 24, 2013, 10:55 am
The shuffling methods in those forum posts are over my head.  Is there some simple example code out there?

#### Nick Gammon

#4
##### Jan 24, 2013, 11:02 am
Code: [Select]
`// -- see: http://en.wikipedia.org/wiki/Fisher-Yates_shufflevoid shuffle (int * t, int n)  {  while (--n >= 2)    {    // n is now the last pertinent index    int k = random (n); // 0 <= k <= n - 1    // Swap    int temp = t [n];    t [n] = t [k];    t [k] = temp;    } // end of while   }  // end of shuffleconst int NUM = 30;  // how manyvoid setup (){  int t [NUM];    // populate table  for (int i = 0; i < NUM; i++)    t [i] = i;      // shuffle it  shuffle (t, NUM);    // print table  Serial.begin (115200);  for (int i = 0; i < NUM; i++)    Serial.println (t [i]);}  // end of setupvoid loop () {}`
Please post technical questions on the forum, not by personal message. Thanks!

http://www.gammon.com.au/electronics

#### zondernaam

#5
##### Jan 24, 2013, 05:35 pm
Thanks Nick, this should get me through it.

Go Up

Please enter a valid email to subscribe