Pages: [1]   Go Down
Author Topic: How to randomize 4 digits in an array?  (Read 431 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 4
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Global Moderator
Dallas
Offline Offline
Shannon Member
*****
Karma: 200
Posts: 12779
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset


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

Offline Offline
Newbie
*
Karma: 0
Posts: 4
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Offline Offline
Newbie
*
Karma: 0
Posts: 4
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Global Moderator
Offline Offline
Brattain Member
*****
Karma: 474
Posts: 18696
Lua rocks!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
// -- 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 () {}
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 4
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks Nick, this should get me through it.
Logged

Pages: [1]   Go Up
Jump to: