-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandom_number.js
54 lines (42 loc) · 1.85 KB
/
random_number.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**Math.floor() and Math.ceil() and Math.round()
Math.floor(2.6)=>2
Math.floor(2.2)=>2
Math.ceil(2.2)=>3
Math.ceil(2.6)=>3
Math.round(2.6)=>3
Math.round(2.2)=>2
**/
//1. Getting a random number between two values
/**This example returns a random number between the specified values.
The returned value is no lower than (and may possibly equal) min, and is less than (and not equal) max..
It can include decimal numbers also**/
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
getRandomArbitrary(2,6);
getRandomArbitrary(4,9);
//2. Getting a random integer between two values
/**This example returns a random integer between the specified values.
The value is no lower than min (or the next integer greater than min if min isn't an integer), and is less than (but not equal to) max.
It will be alwayes integer**/
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
getRandomInt(3,7);
getRandomInt(2,9);
//3.Getting a random integer between two values, inclusive
/**While the getRandomInt() function above is inclusive at the minimum, it's exclusive at the maximum.
What if you need the results to be inclusive at both the minimum and the maximum?
The getRandomIntInclusive() function below accomplishes that.**/
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
}
getRandomIntInclusive(3,7);
getRandomIntInclusive(2,9);
//Get a random item from an array using Math.random()
var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];
var randomItem = items[Math.floor(Math.random() * items.length)];