Search code examples
javascriptjquerymathmathematical-optimization

Distributed probability of an array - Javascript


Given this array

{"easy"=>85%, "medium"=>10%, "hard"=>3%, "very hard"=>2%}

I have to add an amount and distribute the possible result thru the probability of getting it.

Example of result:

Added 10 "amounts"
Result:
Easy -> 8 amounts
Medium -> 2 amounts
Hard -> 0 amounts
very hard-> 0 amounts

What would be the best way to do this without a lot of ifs and calculations, any formula?


Solution

  • You can do this using a generic map function that accepts object inputs -

    const map = (t, f) =>
      Object.fromEntries(Object.entries(t).map(([k,v]) => [k,f(v)]))
    
    const amounts = (t, n) =>
      map(t, v => Math.round(n * v)) // <- use `map` here
    
    const input =
      {easy:0.85, medium:0.1, hard:0.03, vhard:0.02}
      
    console.log(amounts(input, 10))

    {
      "easy": 9,
      "medium": 1,
      "hard": 0,
      "vhard": 0
    }