Home > Mobile >  Create a Javasscript Random function with different probability
Create a Javasscript Random function with different probability

Time:11-16

let there be a randomizer function with an argument array of characters

  CustomRandom(['b','c','a','z']){
}

the function returns a random character from the given input array

How can we write the code so that the probability of character returns is according to its index order in the array? like the probability of returning characters should be b<c<a<z

e.g if we run the function 100 times the output can be

 b=>10,
  c=>20,
  a=>30,
  z=>40

they should not compulsorily return given value only.

CodePudding user response:

One simple option would be to create a string like bccaaazzzz:

s = [...'bcaz'].map((c, i) => c.repeat(i   1)).join('')

and then pick randomly from that string.

  • Related