Problems Generating Random Numbers

hi guys
im trying to generate three different, random, numbers per cycle of the code however i don’t understand why i’m getting the outputs i’m getting. To my mind all three of the “TESTs” should give me the same values. instead thy r all different and all unusable due to duplicate values.
Im really more interested in knowing why it is not working as i think it should than simply being told how i should have written the code.

anyway, the questions id like answered are:

  1. why dose “TEST 1” give the same value for the 1st & 2nd variable?
  2. why dose “TEST 2” give the same value all variable?
  3. why is the 1st variable in “TEST 2” always “0”?
  4. why cant i combine line 15 & 16? like so: “ran[r] = random(0,255);” if i do combine them, i get some crazy numbers!

thanks for the help

int r; //couter forloop random number genereator
int ran[]={};// array containing 3 random numbers
int RedBri[] = {}; 
int GreenBri[]={}; 
int BlueBri[]={}; 
int prox;

void setup() {
Serial.begin(9600); 
randomSeed(analogRead(0)); // generater random value using noise from the analog read pin
}

void loop() {
for(r=0; r<=2; r++){ //loop to generater 3 random numbers
prox = random(0,255);// generate random number
ran[r] = prox;  // stor random number in array
}

RedBri[0]    = ran[0];  // assign random numbers to neopixel value array
GreenBri[0]  = ran[1];  
BlueBri[0]   = ran[2];

Serial.println("     test 1");
Serial.println(ran[0]);         //********TEST 1*********
Serial.println(ran[1]);         //********TEST 1 ********
Serial.println(ran[2]);         //********TEST 1*********

Serial.println("     test 2");
Serial.println(RedBri[0]);     //********TEST 2*********
Serial.println(GreenBri[0]);   //********TEST 2 ********
Serial.println(BlueBri[0]);    //********TEST 2*********



Serial.println("     test 3"); //********TEST 3*********
for(r=0; r<=2; r++){           
Serial.println(ran[r]);
}

Serial.println(" ");
delay (1000);
}
int ran[]={};// array containing 3 random numbers

Nope. array containing 0 random numbers. You forgot to give it a size. That's important. As soon as you add anything to it you are overflowing it and stepping on memory that belongs to something else.

That creates an undefined behavior, so anything it does is correct.

ah! it was that simple! :slight_smile: this is this the problem with being a noob :frowning:

many thanks Delta_G

SavageRodent: ah! it was that simple! :) this is this the problem with being a noob :(

many thanks Delta_G

You know that array variables WILL get the proper number of elements if they are specified ahead of time... like this:

int array[] = { 10, 20, 30, 40, 50 }; // this is now "array[5]" (right)
int array[] = { }; // this is now "array[0]" (useless)
int array[5] = { }; // this is now an empty "array[5]" (right)