Go Down

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

zondernaam

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.

Coding Badly


"Shuffle" is the keyword...
https://www.google.com/search?q=shuffle+random+site:arduino.cc%2Fforum

zondernaam

Thank you for the speedy response, I'll give it a look.

zondernaam

The shuffling methods in those forum posts are over my head.  Is there some simple example code out there?

Nick Gammon

Code: [Select]

// -- see: http://en.wikipedia.org/wiki/Fisher-Yates_shuffle

void 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 shuffle

const int NUM = 30;  // how many

void 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 setup

void loop () {}
Please post technical questions on the forum, not by personal message. Thanks!

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

zondernaam

Thanks Nick, this should get me through it.

Go Up