You can select a random value from the array using the code:

config.targets[Math.floor(Math.random() * config.targets.length)] 

Is it possible to make it so that in 75% of cases the first 10% of the array content is selected?

For example, there is an array with numbers from 1 to 100. It is necessary that 75% of the random number fall into numbers from 1 to 10.

    3 answers 3

    If you need to provide a minimum of 75% probability that randomly selected elements will be in the first 1/10 of the array:

     let max = config.targets.length; if (Math.random() < 0.75) // с вероятностью 75%... max /= 10; // ...сокращаем диапазон до 10% от кол-ва элементов let idx = Math.floor(Math.random() * max); // это результат, "случайный" индекс элемента 

    "Provide" is conditional ... In practice, in some cases it may turn out to be slightly less (the amount of deviation depends on the number of elements, first of all).

     const config = { targets: new Array(100) }; let max = config.targets.length; for (let i = 0; i < max; i++) config.targets[i] = i + 1; const rndTarget = () => { let cMax = Math.random() >= 0.75 ? max : max * 0.1; return config.targets[Math.floor(Math.random() * cMax)]; }; const testVol = 250; for (var test = [], i = 0; i < testVol; i++) test.push(rndTarget()); const tenPercentCount = test.reduce((r, v) => r += v <= 10, 0); console.log(`Из ${testVol} случайно выбранных элементов, ${(tenPercentCount / testVol * 100).toFixed(1)}% в первой 1/10 части массива.\nЧисла:\n${test.join(', ')}`); 

    • one
      Math.random gives numbers from 0 (inclusive) to 1 (not including) ... does this mean that 75% probability is strictly less than 0.75, and not less or equal? - OPTIMUS PRIME
    • @OPTIMUSPRIME is not very important, because random is still not random =) - Stranger in the Q
    • @OPTIMUSPRIME, right, I get 1% extra. Thank you - yar85
    • one
      @OPTIMUSPRIME, Math.random () never returns .75, so it doesn't matter. - Qwertiy

    Divide the number of requests in proportion and in 75% of cases change the sample to the required 10%)

    PS Well, so it is still possible:

     random = Math.round( Math.random() * 100); if ( random >= 0 && random <= 75 ) Math.round( Math.random() * 10); else if ( random > 75 && random <= 100 ) Math.round( Math.random() * 90 + 10); 
    • round is not the topic - it will create an error on the edges, and both borders are achievable. It is necessary to do through the floor. - Qwertiy

     const f = (n, m, p) => () => Math.floor (Math.random () * (Math.random () < p ? m : n)) console.log (Array.from ({length: 100}, f (100, 10, 0.75)))