Overview
In this lesson, students will be introduced to the idea of randomly choosing elements from arrays.
Overview
In this lesson, students will be introduced to the idea of randomly choosing elements from arrays.
Suggested Duration
45 minutes
Objectives
Students will be able to:
Student Outcomes
Abstraction:
Algorithms:
Prototype:
Vocabulary
Array | An ordered series of data |
---|---|
Index | A position within an array |
Element | A piece of data within an array |
Zero-Indexed | The first element of an array has an index of 0, not 1 |
random() |
Returns back a random number in between its parameters |
floor() |
Returns the input number rounded down |
Resources
What Are the random() and floor() functions?
The random()
function does one amazing thing - it gives us a number, randomly chosen. Thankfully, it's controlled chaos. We can tell the random function that we want a number between, say, 3 and 7. Or 5.894858 and 9.483984.
If I write var num = random(4, 9);,
num
will be equal to a number that is greater than or equal to four, and less than nine. The problem there is that that number could very well be 5.93943. If we want to be able to use this function to pick an element from an array, we need to make sure that the random() function is returning a whole number.
In order to do this, we can use another function called floor()
. This will take any decimal number and round it down to the nearest whole number. floor(5.9058588585)
will equal 5, as will floor(5.48484)
and floor(5.00000)
.
So if we have an array called "colors" with 4 elements in it, we could run the following code:
And the console output would be a random element from that array.
If we don't know the length of the array or we want to keep changing it, we can use the array length property. Luckily arrays can store properties about themselves, such as the size or current length of the array. For example console.log(words.length)
will print you the current length of an array called words
.
So we could say random(0, colors.length)
.
Exercise #1: Pull Values From An Array To Set Or Change The Color Of Multiple Shapes
Let’s set up a sketch with a few shapes. In my example, I’ve included a rectangle and a circle. Declare an array with colors in it, and set the colors equal to randomly chosen elements from that array. See the example for how to do that! Now, every time you reload the sketch, the shapes will update with different colors.
Exercise #2: Fortune Cookie Message Generator
Pick 10 fortune cookie messages from this list, store them in an array, and whenever the user loads the sketch, a different text message will be displayed.
Extensions
Use random()
and multiple arrays to create one of the following: