Having random select from limited choices

Hello!

This is a pretty basic question but I haven’t found the answer yet. I’m working with some code from the loop tutorial to fill a screen with gray rectangles, each assigned a random lightness. I’ve posted my code below.

What if I wanted the program to generate the fill from a selection of only 2 or 3 colors… Something like "create rectangle with fill(255,0,0) OR fill(0,255,0)

Here’s the program right now:

float sqr = 100;

size (900,900);
background(0);
noStroke();
  
for (float y = 0; y < height; y = y + sqr) {
  for (float x = 0; x < width; x = x + sqr) {
  fill(random(255));
  rect(x, y, sqr, sqr);
  }
}

Thanks!
-Paul

1 Like

Welcome! Please format forum code with the </> button, or add three ticks around it. I’ll edit your post to demonstrate.

There are many ways to do what you want.

One simple way is to combine an array (a list of things) with a random integer (a choice about which item in the array to use).

Examples of arrays and random numbers:

…and here is a sketch combining them to pick a new random background color when you press any key.

https://editor.p5js.org/jeremydouglass/sketches/omwYbCOKw

You can load the three colors in an array and then you can retrieve any of these three colors by using the modulos operator (%). Since there are three colors, you can try value%3 which will return the following values depending on value: 0, 1, 2. You can use these values as the index of your color array.

int indexColor = value % colorArray.size();
color c = colorTable[indexColor];

Kf