in

Generate random numbers using Math.random() in JavaScript

1663565358random numbers js

[ad_1]

In this article, we’ll look at how to generate random numbers in JavaScript. Math.random()load random images, select random elements from arrays, generate random colors, characters, strings, phrases, and passwords, and build reusable functions for a wide range of purposes.

Randomness in JavaScript

It’s always nice to be able to add an element of randomness to your program. You may want to spice up your website by adding random styles, generating random phrases, or adding an element of chance to your game (for example, in this Numble game these are widely used).

Unfortunately, creating truly random values ​​is actually very difficult (unless you have access to radioactive material or use a monkey with a keyboard). To avoid this, programming languages ​​generate using deterministic methods. pseudorandom number.these are numbers appear Random, but actually generated by a function that accepts seed value Based on events such as mouse pointer time and position.

in JavaScript random Functions that are built-in methods Math object. The ECMAScript standard does not specify how this function generates random numbers, so implementation is left to browser vendors. At the time of this writing, all major browsers use his xorshift128+ algorithm in the background to generate pseudo-random numbers.

To use, simply enter Math.random() and returns a pseudorandom floating point decimal number between 0 (inclusive) and 1 (exclusive).

const x = Math.random();

This can be expressed as the following inequality:

0 <= x < 1

But what if you want a random number greater than 1? Easy: Just multiply and zoom in. For example, multiplying the result by 10 produces a value between 0 (inclusive) and 10 (exclusive).

const y = Math.random()*10

The reason for this can be seen by multiplying both sides of the previous inequality by 10.

0 <= y < 10

However, the result is still a floating point decimal number. What if we want a random integer? Simple: all we need to do is Math.floor Use a function to round the return value to an integer below. The following code assigns a random integer between 0 and 9 to a variable. z:

const z = Math.floor(Math.random()*10)

Note that multiplying by 10 only returns values ​​up to 9.

You can generalize this method to create a function that returns a random integer between 0 and up to 0. but does not includea number provided as an argument:

function randomInt(number){
  return Math.floor(Math.random()*(number))
}  

You can use this function to return a random number between 0 and 9.

const randomDigit= randomInt(10)

Now you have a way to create random integers. But what about random integers between two different values ​​that don’t necessarily start at zero? Using the code above, addition Value to start the range with. For example, if you want to generate a random integer between 6 and 10, use the code above to generate a random integer between 0 and 4 and add 6 to the result.

const betweenSixAnd10 = Math.floor(Math.random()*5) + 6

to generate a random integer between 0 When 4actually had to hang 5.

You can generalize this method to create a function that returns a random integer between two values.

function randomIntBetween(min,max){
  Math.floor(Math.random()*(max - min + 1)) + min
}   

This is a simple generalization of the code I wrote to get a random number between 6 and 10, but with 6 as min parameter and 10 is max parameters. To use it, simply enter two arguments representing the upper and lower bounds of the random number (inclusive). So to simulate rolling a hexahedral die, you can use the following code to return an integer between 1 and 6.

const dice = randomIntBetween(1,6)

How randomIntBetween the function works. In the demo below I am connecting to some HTML so you can change the values. min When max Click the button to generate a random integer (this can be used to replicate the various size dice used in Dungeons & Dragons and similar games).

look at the pen
Random Integer – SitePoint by SitePoint (@SitePoint)
with a code pen.

There are some functions for generating random integers, so you can do interesting things with them.

Load random image

first, randomInt Ability to load random photos from the Lorem Picsum website. This site provides a database of placeholder images, each with a unique integer ID. This means that you can create links to random images by inserting random integers into the URL.

Simply set the following HTML to display an image with an ID of 0.

<button id="randomPhoto">Random Photo</button>
<p id="photo"><img src="https://picsum.photos/id/0/200/200"></p>

Then hook the following JavaScript to generate a random integer for the ID and update the HTML to randomly display a new image when the button is clicked.

document.getElementById("randomPhoto").addEventListener("click",e => document.getElementById("photo").innerHTML = `<img src="https://picsum.photos/id/${randomInt(100)}/200/200">`)

You can see this in the CodePen demo below.

look at the pen
Random Photo – SitePoint by SitePoint (@SitePoint)
with a code pen.

Generate random colors

In HTML and CSS, colors are represented by three integers from 0 to 255, written in hexadecimal (base 16). The first represents red, the second represents green, and the third represents blue.This means that we can use randomInt Use a function to generate three random numbers between 0 and 255 and convert them to base 16 to create random colors.To convert a number to another base, replace the argument with toString method, the following code returns a random hexadecimal number between 0 and FF (255 hex).

randomInt(0,255).toString(16)
<< 2B

with this, randomColor Functions that return HTML color codes:

function randomColor(){ 
  return `#${randomInt(1,255).toString(16)}${randomInt(1,255).toString(16)}${randomInt(1,255).toString(16)}`
}

This returns a template literal that starts with a hash character that starts with every HTML color code, and concatenates three random integers between 0 and 255 in hexadecimal at the end.

call randomColor The function returns a random HTML color string.

randomColor()
<< #c2d699

In the CodePen demo below, I’ve connected a function to an HTML button so that the background color of the document changes whenever the button is clicked.

look at the pen
Random Color – SitePoint by SitePoint (@SitePoint)
with a code pen.

Random letter generation

We already have functions to create random integers, but what about random characters? Fortunately, there’s a nice way to convert integers to characters using a base. In base 36, the integers 10 through 35 are represented by the letters ‘a’ through ‘z’. This can be verified by converting some values ​​to base 36 in the console. toString Method:

(24).toString(36)
(16).toString(36)

Knowing this, it’s easy to write: randomLetter functions that use us randomInt A function that generates a random integer between 10 and 35 and returns its base 36 string representation:

function randomLetter(){
 return randomInt(10,35).toString(36)
}

talking randomLetter I need to return a random lowercase letter from ‘a’ to ‘z’.

randomLetter()
<< "o"

randomLetter()
<< "g"

I’ve connected this function to an HTML button, so you can see how it works in the CodePen demo below.

look at the pen
Random Letters – SitePoint by SitePoint (@SitePoint)
with a code pen.

Generate random string

Now that we can create random characters, we can combine them to create random strings.let’s write randomString a function that accepts a single parameter, n — This represents the number of random characters you want in the returned string.You can create random strings by creating an array or length n and, map A method that changes each element to a random character. next, join A method to convert an array to a random string:

function randomString(numberOfLetters){
  return [...Array(numberOfLetters)].map(randomLetter).join``
}

talking randomString(n) should return a random string of n letter:

randomString(5)
<< "xkibb"

randomLetter(3)
<< "bxd"

I’ve connected this function to an HTML button, so you can see how it works in the CodePen demo below.

look at the pen
Random String – SitePoint by SitePoint (@SitePoint)
with a code pen.

select a random element from an array

It is often useful to be able to select random elements from an array.This can be done fairly easily using our randomInt function. You can randomly choose an index in an array by using the length of the array as an argument and returning the element at that index from the array.

function randomPick(array){
 return array[randomInt(array.length)]
}

For example, with the following array representing a list of fruits:

const fruits = ["🍏",🍌","🍓","🥝","🍋","🍐","🫐","🍉"]

You can use the following code to pick a fruit randomly.

randomPick(fruits)
<< "🍉"

generate random phrases

Now that we have a function that selects a random element from the array, we can use it to create a random phrase. This technique is often used as placeholder usernames on websites. First, create three arrays as shown below. One contains adjective strings, one contains colors, and other nouns.

const adjectives = ["Quick","Fierce","Ugly","Amazing","Super","Spectacular","Dirty","Funky","Scary"]
const colors = ["Brown","Red","Orange","Black","White","Purple","Pink","Yellow","Green","Blue"]
const nouns = ["Fox","Bear","Monkey","Hammer","Table","Door","Apple","Banana","Chair","Chicken"]

Now that we have these three sequences, it’s easy to create random phrases. randomPick function. Select random elements from each array, concatenate them, and put a space between them to create a clause.

function randomPhrase(a,c,n){
  return `${randomPick(a)} ${randomPick(c)} ${randomPick(n)}`
}

talking randomPhrase It should return a slightly funny-sounding random phrase containing colors, adjectives, and nouns.

randomPhrase()
<< "Funky Pink Chicken"

I’ve hooked this function up to an HTML button, so you can create some wacky phrases by pressing the button in the CodePen demo below.

look at the pen
Random Phrase – SitePoint by SitePoint (@SitePoint)
with a code pen.

Generate random password

The final use of random integers we’ll look at is generating random password strings. A general rule for passwords is that they contain at least:

  • 8 characters
  • one number
  • 1 non-alphanumeric special character

Examples that fit these rules are:

secret!1

We already have a function that can generate each of these elements.First, use randomString(6) Create a random string of 6 characters. next, randomPick Use a function to select special characters from an array, then use randomInt(9) Returns a random number. Now just concatenate them together and you have a randomly generated password!

You can boil this down to a function that returns a random password string.

function generatePassword(){
  return randomString(6) + randomPick(["!","%","?","&","@","£","$","#"]) + randomInt(9)
}

talking generatePassword It should return a random password that passes the above three rules.

generatePassword()
<< "ykkefn@8"

Now that you’ve connected this function to an HTML button, try pressing the button to generate a random password in the CodePen demo below.

look at the pen
Random Password – SitePoint by SitePoint (@SitePoint)
with a code pen.

One thing to note is how all the functions we’ve written so far are randomInt the first function I wrote.of generatePassword For example, the function we just wrote is randomInt,randomPick When randomString function…and randomString the function is randomLetter function! This is the foundation of programming, using functions as building blocks for more complex functions.

summary

We’ve seen how to generate random numbers in JavaScript. I hope you find this guide helpful.of randomInt The function is certainly a nice function to have in your locker and can help add some randomness to your project.

You can see all the examples covered in this article in the following CodePen demos.

look at the pen
Randomness – SitePoint by SitePoint (@SitePoint)
with a code pen.

Related reading:

[ad_2]

Source link

What do you think?

Leave a Reply

GIPHY App Key not set. Please check settings

    Cullen Fischel of Cleveland

    Cleveland’s Cullen Fischel on the future of web design

    moscow large

    The Daily Herald – Zelenskiy calls for punishment of Russia including loss of UN veto