Random number for RGB Led

Hey,
i have 9 RGB Led's. Each of this led should light up red, green or blue. Which color the led lights up should be randomly.
Therefore i wrote this method (which works) but i hope that you can give me a better solution:

int rand=random(0,2);
if(rand == 0) {
lightRed(led1);
}
else if (rand == 1) {
lightGreen(led1);
}
else if (rand == 2) {
lightBlue(led1);
}

int rand2=random(0,2);
if(rand2 == 0) {
lightRed(led2);
}
else if (rand2 == 1) {
lightGreen(led2);
}
else if (rand2 == 2) {
lightBlue(led2);
}
.....

int rand9 = random(0,2);
if(rand9 == 0) {
lightRed(led9);
}
else if (rand9 == 1) {
lightGreen(led9);
}
else if (rand9 == 2) {
lightBlue(led9);
}

....way to much code. There must be a more elegant solution.
Thanks for your help.

int rand=random(0,2);

This will result in rand containing either 0 or 1. The upper limit is the smallest number not returned. Why? A dumb decision by the Arduino team.

i hope that you can give me a better solution

When you find your self doing the same thing over and over, it's time to write a function. That and arrays would eliminate more than 90% of your code.

Yeah sure so my function would be something like

void randomColor(int led) {
int rand = random(0,3);
if (rand == 0) {
colorRed(led);
}
else if (rand == 1) {
colorGreen(led);
}
else if (rand == 2) {
colorBlue(led);
}
}

and then
for (int i = 0;i<ledArray.length;i++) {
randomColor(i);
}

right ?

I will try that out now.

If you had an access routine that worked like this:

void lightLED(int led, int color) { …implementation here… }

You could implement that long section of code as:

lightLED(1, random(0,2));
lightLED(2, random(0,2));
…

-br

You could implement that long section of code as:

Or, even better as:

lightLED(1, random(0,3));
lightLED(2, random(0,3));

Or, even better in a for loop...

The original arrangement of lighting up just one color per led is weird, particularly in light of the multiple leds.

Here is what I would do:

#define LED_RAND(led) do {if (random(0, 2)) lightBlue(led); if (random(0, 2)) lightRed(led); if (random(0, 2)) lightGreen(led);} while (0);

//in your application code:

  LED_RAND(led1); //randomly lite up a led
  LED_RAND(led2); //randomly lite up a led
...
  LED_RAND(led9); //randomly lite up a led

It will produce random patterns on each led, up to 8 combinations (including dark/off).