Randomness and Noise

Resources:

Shiffman - 2.4: The map() Function - p5.js
Shiffman - 2.5: The random() Function - p5.js

The map() Function

The map() function is very useful for converting a number from one domain to another. By domain we mean a range of numbers -- common ones you see in programming are [0 to 255], [-1 to 1], or [0-9], etc. Often times we need to convert values from one domain to another, and map() gives us an easy way to do that.

The syntax for the map(0) function is map(value,start1,stop1,start2,stop2), where start1 and stop1 represent the bounds of the source domain, and start2 and stop2 represent the bounds of the target domain. The value is the number to be converted from the source domain to the target. So if the value you want to convert is the users mouseX, it would make sense for the source domain to be the width of your canvas (start1 = 0 and stop1 = 100).

In the below example, we've mapped the mouseX to the y position of the ellipse. See if you can reverse it, so that the mouseY controls the x position of the ellipse.

Try writing a new map() function that converts the mouseX variable to change a greyscale background from [0-255].

Random Values

Sometimes we don't want our functions to always behave in the same way. Sometimes we want an element of surprise or chance. That could include creating aesthetic variability with randomized colors and shape dimensions. Or it could involve randomizing the functionality of the code, i.e., randomly deciding whether or not some event happens.
Syntax:
var r = random(high);
var r = random(low, high);

randomSeed(int);

random

Let's make a sketch that places an ellipse in a random location at each frame. Let's now modify it to also randomize color.

Random values can also be used for program flow:

Try making a for loop to print 10 random values between -100 and 100. Then assign a seed so the values are repeatable.

Noise is used to create randomized values in a more controllable way. It uses the Perlin Noise technique, developed by Ken Perlin. Steps of 0.005– 0.03 work best for most applications.
noise(x)
noise(x, y)
noise(x, y, z)

Noise can be used to create 2D textures