website-logo

Random number generation is under appreciated

Published: 27 May 2022

Updated: 27 May 2022

#css #javascript #random-color-generator #programming-basics #utility-functions

I can not recall the number of times I ran into situations that required generating a random number to solve a problem. To give you some crazy facts, it has been more than reaching out for a complex data structure like a tree. Some use cases were generating a random delay between request retries, selecting a random index for an array, generating mock data for a graph, etc.

And here we are, where we will need to generate random numbers to implement an RGB color generator.

You will learn to build this

⚠️ Flash Warning ⚠️


Clicking on the “Update Color” button can generate a bright color.

So, how do you generate a random number?

Most programming languages have a utility function in their Math module/class to generate a random number. We will discuss this article in the context of JavaScript, but the concept can be applied to other programming languages.

In JavaScript, you can generate a random number as follows,

const randomNum = Math.random();

The floating-point number generated is between [0, 1). The mathematical notification means the function can produce a floating-point number between 0 (including 0) and 1 (not including 1).

Read the MDN docs for more details.

Creating a random RGB color

Before we proceed, we first need to understand what is a RGB color.

In RGB Color Model, a color is defined as the composition of Red, Green, and Blue primary colors. You can read more about this color model on its Wiki page.

In context of CSS, a RGB color is defined as follows:

The value of for each primary color can be represented as [0, 255] (inclusive).

/** rgb([0,255], [0-255], [0-255]) **/
color: rgb(70, 30, 250);

Implementing a utility color function

So now we have a good understanding of the problem space, which means we need to do the following:

Write a function that generates a random number between 0 and 255
function getRandomFromRgbRange() {
  return Math.floor(Math.random() * 256);
}

Why we multiplied with 256?

The reason is that we want to include 255 into our range. Remember that Math.random() will never generate 1. Let’s take a look at the examples below:

0 * 256 = 0;                  // Math.random generated "0"
0.999999 * 256 = 255.9974    // Math.random generated "0.999999"

What is Math.floor utility function doing?

From our discussions earlier, RGB color model requires an integer number to generate a valid color. The utility function is rounding the provided number to the closest integer value less than or equal to it. From our example above,

Math.floor(0) = 0;
Math.floor(255.9974) = 255;
Write a function that generates a random color

Great, now we can create a new function using our utility function (composition).

// create a new function using our utility funtion
function generateRandomRgbColor() {
  return [
    getRandomFromRgbRange(), // red
    getRandomFromRgbRange(), // green
    getRandomFromRgbRange(), // blue
  ];
}

Yay! We have created something useful by leveraging the power of a single utility function. Let’s jazz things up by creating a Svelte component to see our utility function in action.

Jazz it up with a visual component!

Let’s implement a Svelte component that does the following:

  1. Renders a container that applies a random RGB color.
  2. Renders a button to change the container color with a new random color.
<!-- RandomColorGenerator.svelte -->
<script lang="ts">
  // declare a reactive variable
  let rgbVal = getColor();

  function getRandomFromRgbRange() {
    return Math.floor(Math.random() * 256);
  }

  function generateRandomRgbColor() {
    return [
      getRandomFromRgbRange(), // red
      getRandomFromRgbRange(), // green
      getRandomFromRgbRange(), // blue
    ];
  }

  function getColor() {
    // returns an array
    const colorComposition = generateRandomRgbColor();

    // apply color as a CSS rule, for example, "rgb(23, 12,122)"
    return `rgb(${colorComposition.join(', ')})`;
  }

  // update the reactive variable when button is clicked
  function updateColor() {
    rgbVal = getColor();
  }
</script>

<div class="container">
  <!--  apply the current rgb color as the background color -->
  <div class="box" style:background-color={rgbVal}>
    <p>
      {rgbVal}
    </p>
  </div>
  <!-- add a on click handler for our button to update the container with a random color -->
  <button on:click={updateColor}>Update Color</button>
</div>

<style>
  /* styles for the top level container */
  .container {
    display: flex;
    width: 100%;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  /* styles for button */
  button {
    background-color: rgb(0, 0, 0);
    color: white;
    padding: 10px;
    margin: 15px 0;
  }

  /* styles for container applying the random rgb color */
  .box {
    width: 100%;
    height: 250px;
    border-radius: 5px;
    border: 2px solid black;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  /* styles for the paragraph displaying the applied color */
  p {
    margin: 0;
    font-size: 20px;
    font-weight: bold;
    background-color: rgb(255, 221, 161);
    display: inline-block;
    padding: 10px;
    color: rgb(84, 61, 6);
    border-radius: 5px;
  }
</style>

Component in action

⚠️ Flash Warning ⚠️


Clicking on the “Update Color” button can generate a bright color.

Conclusion

To drive the point home:

  • Math.random is a really cool utility function which can be used to create something useful.
  • Composition allows you to build complex things.

I hope this article gave you inspirations to leverage the power of randomness.



Here is a codepen where I am using Math.random for creating snow in the scene,