Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

137
Visualizações
Generating a random sublist from single random number

There's a fairly simple method in javascript to choose a random element from a list using a single instance of Math.random():

Array.prototype.random_choice = function (seed=Math.random()) {
    return this[Math.floor(seed * array.length)];
}

I'm looking for a way to choose a randomly ordered collection of k elements of an array, similarly using a single use of Math.random(). Here's what I've got so far:

Array.prototype.random_choice = function(k, seed=Math.random()) {
    var array = JSON.parse(JSON.stringify(this)); // deep-copies array
    var n = array.length, u = seed, index = 0, choice = [];
    while (array.length > Math.max(0, n-k)) {
        // index chosen in standard way, as above
        index = Math.floor(u*array.length);
        // next random number is integer part of u*array.length
        u = u*array.length - index;

        choice.push(array[index]);
        array.splice(index, 1);
    }
    return choice;
}

It relies on the integer part of some multiple of u being distributed in the same way as u itself, but I know have a good enough understanding of how Math.random() works to know whether this is valid. Furthermore, if my solution is valid, what are its limitations? I assume that the precision of u is finite - which means it won't work for arbitrarily large arrays - but where is the limit?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda