How to pick a random number in javascript? [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript: Getting random value from an array
I have a list of ten items.
ar = [112,32,56,234,67,23,231,123,12]
How do I choose an item randomly with javascript?

var ar = [112,32,56,234,67,23,231,123,12];
var randomKey = Math.floor(Math.random() * ar.length);
var randomValue = ar[randomKey];
Check out the documentation on the Math object; https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math
You could easily abstract this into a nice function:
function getRandom(array, getVal) {
var key = Math.floor(Math.random() * array.length);
if (getVal) {
return array[key];
}
return key;
}
Then you'd call it like getRandom(ar) to get a random key in the array, and getRandom(ar, true) to return a random value in the array.

well something like
var randnum = Math.floor ( Math.random() * ar.length );
val random = (ar[randnum]);

Related

How can I randomize a number within a range and make every number have equal probability [duplicate]

This question already has answers here:
Getting a random value from a JavaScript array
(28 answers)
Closed 7 years ago.
var items = Array(523, 3452, 334, 31, ..., 5346);
How do I get random item from items?
var item = items[Math.floor(Math.random()*items.length)];
1. solution: define Array prototype
Array.prototype.random = function () {
return this[Math.floor((Math.random()*this.length))];
}
that will work on inline arrays
[2,3,5].random()
and of course predefined arrays
var list = [2,3,5]
list.random()
2. solution: define custom function that accepts list and returns element
function get_random (list) {
return list[Math.floor((Math.random()*list.length))];
}
get_random([2,3,5])
Use underscore (or loDash :)):
var randomArray = [
'#cc0000','#00cc00', '#0000cc'
];
// use _.sample
var randomElement = _.sample(randomArray);
// manually use _.random
var randomElement = randomArray[_.random(randomArray.length-1)];
Or to shuffle an entire array:
// use underscore's shuffle function
var firstRandomElement = _.shuffle(randomArray)[0];
If you really must use jQuery to solve this problem (NB: you shouldn't):
(function($) {
$.rand = function(arg) {
if ($.isArray(arg)) {
return arg[$.rand(arg.length)];
} else if (typeof arg === "number") {
return Math.floor(Math.random() * arg);
} else {
return 4; // chosen by fair dice roll
}
};
})(jQuery);
var items = [523, 3452, 334, 31, ..., 5346];
var item = jQuery.rand(items);
This plugin will return a random element if given an array, or a value from [0 .. n) given a number, or given anything else, a guaranteed random value!
For extra fun, the array return is generated by calling the function recursively based on the array's length :)
Working demo at http://jsfiddle.net/2eyQX/
Here's yet another way:
function rand(items) {
// "~~" for a closest "int"
return items[~~(items.length * Math.random())];
}
Or as recommended below by #1248177:
function rand(items) {
// "|" for a kinda "int div"
return items[items.length * Math.random() | 0];
}
var random = items[Math.floor(Math.random()*items.length)]
jQuery is JavaScript! It's just a JavaScript framework. So to find a random item, just use plain old JavaScript, for example,
var randomItem = items[Math.floor(Math.random()*items.length)]
// 1. Random shuffle items
items.sort(function() {return 0.5 - Math.random()})
// 2. Get first item
var item = items[0]
Shorter:
var item = items.sort(function() {return 0.5 - Math.random()})[0];
Even shoter (by José dB.):
let item = items.sort(() => 0.5 - Math.random())[0];
var rndval=items[Math.floor(Math.random()*items.length)];
var items = Array(523,3452,334,31,...5346);
function rand(min, max) {
var offset = min;
var range = (max - min) + 1;
var randomNumber = Math.floor( Math.random() * range) + offset;
return randomNumber;
}
randomNumber = rand(0, items.length - 1);
randomItem = items[randomNumber];
credit:
Javascript Function: Random Number Generator
If you are using node.js, you can use unique-random-array. It simply picks something random from an array.
An alternate way would be to add a method to the Array prototype:
Array.prototype.random = function (length) {
return this[Math.floor((Math.random()*length))];
}
var teams = ['patriots', 'colts', 'jets', 'texans', 'ravens', 'broncos']
var chosen_team = teams.random(teams.length)
alert(chosen_team)
const ArrayRandomModule = {
// get random item from array
random: function (array) {
return array[Math.random() * array.length | 0];
},
// [mutate]: extract from given array a random item
pick: function (array, i) {
return array.splice(i >= 0 ? i : Math.random() * array.length | 0, 1)[0];
},
// [mutate]: shuffle the given array
shuffle: function (array) {
for (var i = array.length; i > 0; --i)
array.push(array.splice(Math.random() * i | 0, 1)[0]);
return array;
}
}

How to generate random numbers from the given numbers [duplicate]

This question already has answers here:
Get a random item from a JavaScript array [duplicate]
(13 answers)
Getting a random value from a JavaScript array
(28 answers)
Closed 3 years ago.
I have an scenario to generate random numbers that should generate from the given numbers.
for example, I have an array num=[23,56,12,22]. so i have to get random number from the array
You can do something like this:
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
let num=[23,56,12,22];
let randomPosition = getRandomInt(num.length);
console.log(num[randomPosition])
you can generate a random index between 0 and array.length - 1
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function getRandomIntFromArray(array) {
return array[getRandomInt(array.length)]
}
const num = [23,56,12,22]
getRandomIntFromArray(num)
Use Math.floor(Math.random() * x), where x is the length of the Array to generate a random number between 0 and the max index
const data = [23,56,12,22]
function randomIndex (array) {
return array[Math.floor(Math.random() * array.length)];
}
console.log(randomIndex(data));
You can make a function that returns a random integer between 0 and the length of the array, like this:
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
Then call it, like this:
let randomInt = getRandonInt(lengthOfArray);
console.log(randomInt);
Expected output: 0, 1, 2 .. length of array
Then just simply use the randomInt to get whatever you need from your array entries.
How about drawing a uniform distributed random integer in the interval [0,len(num)-1] which represents the index of the number you draw from your array num.
This is a very simple and straight forward approach.

Apply a blinking effect with scaling on every li item of ul items randomly using javascript [duplicate]

This question already has answers here:
Getting a random value from a JavaScript array
(28 answers)
Closed 7 years ago.
var items = Array(523, 3452, 334, 31, ..., 5346);
How do I get random item from items?
var item = items[Math.floor(Math.random()*items.length)];
1. solution: define Array prototype
Array.prototype.random = function () {
return this[Math.floor((Math.random()*this.length))];
}
that will work on inline arrays
[2,3,5].random()
and of course predefined arrays
var list = [2,3,5]
list.random()
2. solution: define custom function that accepts list and returns element
function get_random (list) {
return list[Math.floor((Math.random()*list.length))];
}
get_random([2,3,5])
Use underscore (or loDash :)):
var randomArray = [
'#cc0000','#00cc00', '#0000cc'
];
// use _.sample
var randomElement = _.sample(randomArray);
// manually use _.random
var randomElement = randomArray[_.random(randomArray.length-1)];
Or to shuffle an entire array:
// use underscore's shuffle function
var firstRandomElement = _.shuffle(randomArray)[0];
If you really must use jQuery to solve this problem (NB: you shouldn't):
(function($) {
$.rand = function(arg) {
if ($.isArray(arg)) {
return arg[$.rand(arg.length)];
} else if (typeof arg === "number") {
return Math.floor(Math.random() * arg);
} else {
return 4; // chosen by fair dice roll
}
};
})(jQuery);
var items = [523, 3452, 334, 31, ..., 5346];
var item = jQuery.rand(items);
This plugin will return a random element if given an array, or a value from [0 .. n) given a number, or given anything else, a guaranteed random value!
For extra fun, the array return is generated by calling the function recursively based on the array's length :)
Working demo at http://jsfiddle.net/2eyQX/
Here's yet another way:
function rand(items) {
// "~~" for a closest "int"
return items[~~(items.length * Math.random())];
}
Or as recommended below by #1248177:
function rand(items) {
// "|" for a kinda "int div"
return items[items.length * Math.random() | 0];
}
var random = items[Math.floor(Math.random()*items.length)]
jQuery is JavaScript! It's just a JavaScript framework. So to find a random item, just use plain old JavaScript, for example,
var randomItem = items[Math.floor(Math.random()*items.length)]
// 1. Random shuffle items
items.sort(function() {return 0.5 - Math.random()})
// 2. Get first item
var item = items[0]
Shorter:
var item = items.sort(function() {return 0.5 - Math.random()})[0];
Even shoter (by José dB.):
let item = items.sort(() => 0.5 - Math.random())[0];
var rndval=items[Math.floor(Math.random()*items.length)];
var items = Array(523,3452,334,31,...5346);
function rand(min, max) {
var offset = min;
var range = (max - min) + 1;
var randomNumber = Math.floor( Math.random() * range) + offset;
return randomNumber;
}
randomNumber = rand(0, items.length - 1);
randomItem = items[randomNumber];
credit:
Javascript Function: Random Number Generator
If you are using node.js, you can use unique-random-array. It simply picks something random from an array.
An alternate way would be to add a method to the Array prototype:
Array.prototype.random = function (length) {
return this[Math.floor((Math.random()*length))];
}
var teams = ['patriots', 'colts', 'jets', 'texans', 'ravens', 'broncos']
var chosen_team = teams.random(teams.length)
alert(chosen_team)
const ArrayRandomModule = {
// get random item from array
random: function (array) {
return array[Math.random() * array.length | 0];
},
// [mutate]: extract from given array a random item
pick: function (array, i) {
return array.splice(i >= 0 ? i : Math.random() * array.length | 0, 1)[0];
},
// [mutate]: shuffle the given array
shuffle: function (array) {
for (var i = array.length; i > 0; --i)
array.push(array.splice(Math.random() * i | 0, 1)[0]);
return array;
}
}

How to get a random number from an Array without repetition in Javascript? [duplicate]

This question already has answers here:
Generating non-repeating random numbers in JS
(20 answers)
Closed 3 years ago.
I am trying to return a random number from an array of numbers i.e. cardNumbertemp.
function cardRandomiser(){
randomCard = Math.floor(Math.random()*cardNumbertemp.length);
for (var i = 0; i < cardNumbertemp.length; i++){
if (randomCard === cardNumbertemp[i]){
cardNumbertemp.splice(i,1);
return randomCard;
}
}
}
This function needs to return a single random number from the array (cardNumbertemp) then remove the number from the array. It works however sometimes it returns undefined.
If you are looking to getting a random number, you can use the below code. You ideally need not splice unless you do not intend to have that number again.
var cardNumbertemp = [45, 78, 23, 89];
(function() {
console.log(getRandom());
})();
function getRandom() {
randomCard = Math.floor(Math.random() * cardNumbertemp.length);
return cardNumbertemp[randomCard];
}
let cardNumbertemp = [45, 78, 23, 89];
for(let i = 0; i < cardNumbertemp.length + i; i++){
// will give you random number b/w 0 & (length of given array - 1)
let randomIndex = Math.floor((Math.random() * cardNumbertemp.length));
console.log(cardNumbertemp[randomIndex]); // output random array value
cardNumbertemp.splice(randomIndex, 1); // maintain unique random value
}

How to add a comma in my increasing number via JS? [duplicate]

This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 8 years ago.
I'm trying to add a comma between my 20000 to show as 20,000 without it messing up and have gotten pretty close but trying to fill in the next steps. Below, I've listed my code with the function thats able to do it but trying to connect the two together to properly work.
Here is my jsFiddle!
And code..
HTML
<span id="liveNumbers">23000</span>
JS
setInterval(function(){
random = (Math.floor((Math.random()*2)+1));
var plus = Math.random() < 0.5 ? 1 : 1;
random = random * plus;
currentnumber = document.getElementById('liveNumbers');
document.getElementById('liveNumbers').innerHTML = parseInt(currentnumber.innerHTML) + random;
}, 3000);
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
return val;
}
You'd have to change your initial value to include a comma or do an initial run before the setInterval is started but something like this might work:
setInterval(function(){
random = (Math.floor((Math.random()*2)+1));
var plus = Math.random() < 0.5 ? 1 : 1;
random = random * plus;
currentnumber = document.getElementById('liveNumbers');
var curnum = parseInt(currentnumber.innerHTML.replace(",",""));
document.getElementById('liveNumbers').innerHTML =
commaSeparateNumber(curnum + random);
}, 3000);
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
return val;
}

Categories

Resources