Getting a random value from a JavaScript array
It's a simple one-liner:
const randomElement = array[Math.floor(Math.random() * array.length)];
For example:
const months = ["January", "February", "March", "April", "May", "June", "July"];
const random = Math.floor(Math.random() * months.length);
console.log(random, months[random]);
Get a random item from a JavaScript array
var item = items[Math.floor(Math.random()*items.length)];
pick a random item from a javascript array
Use Math.random * the length of the array, rounded down, as an index into the array.
Like this:
var answers = [ "Hey", "Howdy", "Hello There", "Wotcha", "Alright gov'nor"]
var randomAnswer = answers[Math.floor(Math.random() * answers.length)];
console.log(randomAnswer);
How to Randomly Choose an Element from an Array that Wasn't Chosen before in JavaScript?
You can try something like this:
Idea
- Create a utility function that takes an array and returns you a random value.
- Inside this Array, maintain 2 array, choices and data.
- In every iteration, remove 1 item from
data
and put it inchosenItems
- Once the length of
data
reaches0
, setchosenItems
ororiginalArray
as data and repeat process.
Benefit of this approach would be,
- You dont need to maintain and pass array variable.
- It can be made generic and used multiple times.
function randomize(arr) {
let data = [...arr];
let chosenItems = [];
function getRandomValue() {
if (data.length === 0) {
data = chosenItems;
chosenItems = [];
}
const index = Math.floor(Math.random() * data.length);
const choice = data.splice(index, 1)[0];
chosenItems.push(choice);
return choice;
}
return {
randomItem: getRandomValue
}
}
const dummyData = [ 1,2,3,4,5 ];
const randomizeData = randomize(dummyData);
for (let i = 0; i< 10; i++) {
console.log(randomizeData.randomItem())
}
How to get a number of random elements from an array?
Try this non-destructive (and fast) function:
function getRandom(arr, n) {
var result = new Array(n),
len = arr.length,
taken = new Array(len);
if (n > len)
throw new RangeError("getRandom: more elements taken than available");
while (n--) {
var x = Math.floor(Math.random() * len);
result[n] = arr[x in taken ? taken[x] : x];
taken[x] = --len in taken ? taken[len] : len;
}
return result;
}
How do I pick randomly from an array?
Just use Array#sample
:
[:foo, :bar].sample # => :foo, or :bar :-)
It is available in Ruby 1.9.1+. To be also able to use it with an earlier version of Ruby, you could require "backports/1.9.1/array/sample"
.
Note that in Ruby 1.8.7 it exists under the unfortunate name choice
; it was renamed in later version so you shouldn't use that.
Although not useful in this case, sample
accepts a number argument in case you want a number of distinct samples.
How to pick a random value out of an array with a specific proportion?
You can have an array of size 20 that contains the relative portion of your labels, and represent the exact percentage of each label.
Then, all you need to do is random of 1-20, the result will use as index to choose from the array.
var diffSev = [
'CRITICAL',
'ERROR', 'ERROR',
'INFO', 'INFO', 'INFO', 'INFO', 'INFO', 'INFO',
'DEBUG', 'DEBUG', 'DEBUG', 'DEBUG', 'DEBUG', 'DEBUG', 'DEBUG', 'DEBUG', 'DEBUG', 'DEBUG', 'DEBUG'
]
return diffSev[Math.floor(Math.random() * 20)];
Get random item from array
echo $items[array_rand($items)];
array_rand()
Picking a random item from array with equal distribution
If you can precompute the result (i.e. you need a finite number of results, not an infinite stream) and the number of results is divisible by the number of items, you can get a perfect distribution:
- Generate an array that repeats the items until you've got enough, i.e.
[1, 2, 3, 1, 2, 3, 1, 2, 3, ...]
. The array is thus guaranteed to have exactly as many instances of each item. - Shuffle the array with a fair shuffle algorithm, e.g. Fisher-Yates. The array still has exactly as many instances of each item.
If you do need an infinite stream, you could use something like an "item bag" model (which, btw, is how the blocks in Tetris are chosen):
- Fill a "bag" with your items (
[1, 2, 3]
). Shuffle it (as above). - When you need an item, pop the first one from the shuffled bag.
- If the bag is empty, re-fill it according to step 1.
The only case where this doesn't have a perfect distribution is if you stop "mid-bag".
Selecting 3 random elements from an array in python
You can use random.sample(), if you want to sample without replacement, ie. the same element can't be picked twice.
>>> import random
>>> l = [0.3, 0.2, 0.1, 0.4, 0.5, 0.6]
>>> random.sample(l, 3)
[0.3, 0.5, 0.1]
If you want to sample with replacement, you can random.choices()
>>> import random
>>> l = [0.3, 0.2, 0.1, 0.4, 0.5, 0.6]
>>> random.choices(l, k=3)
[0.3, 0.5, 0.3]
Related Topics
Difference Between Require_Relative and Require in Ruby
Difference Between Include and Extend in Ruby
How to Match All Occurrences of a Regex
How to Install Postgresql'S Pg Gem on Ubuntu
Rails: Access to Current_User from Within a Model in Ruby on Rails
Usage of Attr_Accessor in Rails
Error Installing Libv8: Error: Failed to Build Gem Native Extension
Why Isn't the Eigenclass Equivalent to Self.Class, When It Looks So Similar
How to Convert a Unix Timestamp (Seconds Since Epoch) to Ruby Datetime
Heroku - Cannot Run Git Push Heroku Master
Does Ruby Have Real Multithreading
What Is the Best Method of Handling Currency/Money
How to Modify Path For Homebrew
Disable Activerecord For Rails 4