# I want a random color generator that repeats

#1

I have been trying to figure this out and have been able to nail it

#2

Do you want to create a random sequence of colors which repeats over and over?

• red, green, white, red, green, white, …
• blue, yellow, yellow, yellow, blue, yellow, yellow, yellow, …

You can first create an array filled with random colors and then loop through the array as many times as you like:

1. Create an array with random colors and store it in `pattern`
``````var pattern = [
pickRandom(color),
pickRandom(color),
pickRandom(color)
];
``````
1. Loop through the `pattern` array and draw all the colors
``````var numberOfLoops = 5;
for (var loops = 0; loops < numberOfLoops; loops = loops + 1) {
for (var element of pattern) {
drawBox(element);
}
}
``````

1. What if you want different sized patterns?
``````var patternLength = 3;
var pattern = [];
for (var i = 0; i < patternLength; i = i + 1) {
pattern.push(pickRandom(color));
}
``````
1. What if you want to end before finishing the whole pattern?
``````var numberOfBoxes = 5;
var i = 0;
for (var box = 0; box < numberOfBoxes; box = box + 1) {
drawBox(pattern[i]);
i = i + 1;
if (i >= patternLength) {
i = 0;
}
}
``````

Some simplifications:

A `let` is like `var` but the variable name only exists inside of its code block `{}`. This is useful in case you want to use another `pattern` variable somewhere else in your code to store a different pattern.

``````let patternLength = 3;
let pattern = [];
let numberOfBoxes = 5;
``````

`i++` is the same as `i = i + 1`

``````for (let i = 0; i < patternLength; i++) {
pattern.push(pickRandom(color));
}
``````

`%` gives the remainder. If you use `5 % 3`, you keep subtracting `3` from `5` without going past 0, you get 2.
Another example:
`13 % 5`:
`13 - 5 === 8``8 - 5 === 3``3 - 5 === -2` which crosses over `0` so that’s too far. The last good value was `3`. We can use the remainder to make a number that’s always less than the length of the pattern.

``````for (let box = 0; box < numberOfBoxes; box++) {
drawBox(pattern[box % patternLength]);
}
``````

If we use a `patternLength` of 3, and keep raising the value of `box`, we get:

box box % patternLength
0 0 % 3 === 0
1 1 % 3 === 1
2 2 % 3 === 2
3 3 % 3 === 0
4 4 % 3 === 1
5 5 % 3 === 2

Notice how the value of `box % patternLength` keeps getting reset to `0` instead of going over the value of `patternLength`.

Putting the code all together:

``````let patternLength = 3;
let pattern = [];
let numberOfBoxes = 10;

for (let i = 0; i < patternLength; i++) {
pattern.push(pickRandom(color));
}

for (let box = 0; box < numberOfBoxes; box++) {
drawBox(pattern[box % patternLength]);
}
``````

–Frankie