-3
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"]
RYOHOI
  • 53
  • 1
  • 4

2 Answers2

1

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);
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • Neat answer! One question, how can a array be shuffled like that? – RYOHOI Dec 18 '14 at 10:15
  • @RYOHOI I just used one of the shortest ways to shuffle the array with sorting by random function. It is far not the best algorithm but can be used for small arrays. Alternatively you may pick one of solutions listed here: http://stackoverflow.com/q/2450954/1249581. – VisioN Dec 18 '14 at 10:17
0

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.

JMP
  • 4,417
  • 17
  • 30
  • 41