The title basically describes my problem... I wanted to get 3 elements from an array list without getting a duplicate. Because the others I have found uses the Math.floor((Math.random() * list.length))
which I think is only limited to one output.
Asked
Active
Viewed 185 times
0

TofuBoy
- 11
- 3
-
1Take a look at thismaybe? [how-to-get-a-number-of-random-elements-from-an-array](https://stackoverflow.com/questions/19269545/how-to-get-a-number-of-random-elements-from-an-array) – Mara Black Nov 22 '20 at 11:45
-
Then do it 3 times – casraf Nov 22 '20 at 11:45
-
Thanks Mara Black :) also casraf, if I just do it 3 times there's a possibility to get a duplicate. anyways~ – TofuBoy Nov 22 '20 at 12:04
-
1Just [shuffle the array](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) and grab the first three elements – Lioness100 Nov 22 '20 at 12:23
1 Answers
0
n unique elements from a set are a combination.
Without getting in too much detail,
combinations = variations * permutations
, which means we can just generate a variation (of the same length) and ignore the order.
The Fisher-Yates shuffle can do this for example:
function shuffled(elements){
// Return shuffled elements such that each variation has the same probability
const copy = [...elements];
for(let i = copy.length - 1; i >= 0; i--){
let j = Math.floor(Math.random() * (i + 1)); // 0 <= j <= i
let tmp = copy[i];
copy[i] = copy[j];
copy[j] = tmp;
}
return copy;
}
function choose(elements, n){
// Return a combination of n elements
return shuffled(elements).slice(0, n);
}
var elements = ['a', 'b', 'c', 'd'];
var N = 1000;
var results = {}; // how many times each element was chosen
for(let i = 0; i < N; i++){
for(let x of choose(elements, 3)){
results[x] = (results[x] || 0) + 1;
}
}
console.log(results); // 3/4 * N = 750

Patrolin
- 106
- 1
- 5