var ramdomCharacters = ["a", "c", "z", "d", "f", "i", "u"];
I want to extract a subset ramdomly from ramdomCharacters, which has a random length and non-repeated item. Like this:
subset = ["c", "f", "i"]
or
subset = ["a", "u"]
var ramdomCharacters = ["a", "c", "z", "d", "f", "i", "u"];
I want to extract a subset ramdomly from ramdomCharacters, which has a random length and non-repeated item. Like this:
subset = ["c", "f", "i"]
or
subset = ["a", "u"]
One possible way is to randomise the array and extract first n
elements:
var randomCharacters = ['a', 'c', 'z', 'd', 'f', 'i', 'u'];
var clone = [].slice.call(randomCharacters), // clone not to alter the original
n = Math.random() * clone.length + 1, // `n` may vary upon your needs
subset = clone.sort(function() {
return 0.5 - Math.random(); // shuffle array
}).slice(0, n); // slice first `n` elements
console.log(subset);
You could try:
var randomCharacters = ['a', 'c', 'z', 'd', 'f', 'i', 'u'];
var subset=[];
while (randomCharacters.length>0)
{
dummy=randomCharacters.pop();
if (Math.random()<0.5) subset.push(dummy);
}
document.write(subset);
This varies from the previous answer in that (1) randomCharacters ends up as [], (2) the final value of 'subset' might be [] and (3), although random, the order of 'subset' is effectively the same as the reverse order of randomCharacters.