java SecureRandom nextInt() vs nextGaussian()

2019-08-09 07:42发布

问题:

Problem statement: Reward a customer with lucky draw coupon of X% discount in between 1% to 100%

Assume that slabs are pre-defined ( all are theoretical)

1% discount : 90% customers

10% discount : 5% customers

20% discount : 3% customers

100% discount : 2% customers

Solution 1:

For every 100 customers, I will pre-populate a random array of size 100 with a good shuffling algorithm

90 1s ( 1 = 1% discount)

5 10s ( 10 = 10% discount)

3 20s ( 20% discount )

2 100s ( 100% discount)

Whenever a customer comes, I will draw random.nextInt(100) and get discount percentage

Solution 2:

Use nextGaussian() of SecureRandom since it is a distributed randomness algorithm.

Which one is more accurate if we want to follow the % strictly?

Refer to example 1 and 3 in Random

Thanks in advance.

回答1:

The distributions are uniform, so Gaussian distribution would be of limited use in this situation. Uniform distributions are what you need.

My understanding of the problem that you're facing is that you want the outcome to have a certain distribution (too many discounts could be very expensive) but otherwise it should be random as in unpredictable. If you just took an arrangment of the 100 possible discounts, sorted them, and used them in a cycle, the arrangement would be predictable. Even if you changed the order for each cycle of 100, someone paying attention might know when the odds of getting a good discount would be higher or lower than normal (sort of like counting cards in Blackjack).

What I think you need instead is a Reservoir Sampling algorithm. The easiest scenario is if you know how many items there will be altogether (how many discount coupons, say) and if there are two categories (winner, loser). Then the code in the Wikipedia article can be used as-is. The problem seems to have less literature with multiple categories (100%, 20%, 10%, 1%), and not knowing the full number of coupons (if it's a time-limited promotion, say). I'll keep looking for papers on the topic, but that's the general idea, I think.



回答2:

Which one is more accurate if we want to follow the % strictly? e.g give 100% discount to 1 customer from every 100 customers.

Neither, because that's no longer random. If you want an exact distribution over a given interval, you'll have to use a different strategy. Populate a Collection with the distribution of values you want, shuffle it, and assign the values to your customers.



回答3:

I suppose accuracies are same. But I would prefer nexInt because it is easier to calculate slabs in this case.



标签: java math random