lundi 20 mai 2019

How to generate random numbers such that probability rise as value increase?

So this is a problem I saw from an interview, say we have two ads slots on a webpage, and also we have several ads, for example, total of 4. Ads are tagged from 1, in this case, we have ads 1, 2, 3, and 4. Question is we need to write a function, with input of total number of ads, return 2 ads from 4 while meeting following requirements:

  1. ads on two slots are different.
  2. if we run the function m times, probability for each ad showing up is 1 : 2 : 3 : 4. Which means if the function is called 5 times, then an expected outcome would be 4 times ad 4, 3 times ad 3, 2 times ad 2, and 1 time ad 1.

follow up: is there a common solution we can solve for n ads, while the chance they can show up on webpage is 1 : 2 : 3 : ... : n-1 : n?

Since the probability of ads rise as the tag number increases, I thought about using segments to solve the problem, if the random number >= 0 and < 0.4 then choose 4, it is easy to get the first slot done, but for the second slot I have no idea how can I handle that.




Aucun commentaire:

Enregistrer un commentaire