Weighted random in the game development of heavy use, a variety of sweepstakes and explosive equipment.
Operations to configure the probability of each item appearing as needed.
That's what we're going to say today. The idea of the weighted stochastic algorithm is very simple, that is, " all the items according to their weights constitute a range, the weight of large interval large." You can imagine a pie chart. Then, throw the dice and see what interval it falls in,"
For a chestnut, there is a year-end lottery, the item is Iphone/ipad/itouch.
The weight of the organizer configuration is [(' iphone ', ' Ten '), (' ipad ', ' Max '), (' itouch ', 50)].
A line of code to illustrate its idea , namely Random.choice ([' iphone ']*10 + [' ipad ']*40 + [' itouch ']*50].
Below, we write a general function.
#coding =utf-8import randomdef weighted_random (items): Total = SUM (w for _,w in items) n = random.uniform (0 ) #在饼图扔骰子 for X, W in items: #遍历找出骰子所在的区间 if n<w: break N-= w return xprint weighted_random ([(' iphone ', ten), (' ipad ', ' Max '), (' itouch ', 50)])
The above code is intuitive enough, but the careful will find that each time will be calculated total, each time the linear traversal of the interval to reduce operations. Actually, we can save it first, look it up. Use accumulate+bisect binary search.
The more items, the better the performance of the two-point lookup.
#coding =utf-8class weightrandom: def __init__ (self, items): weights = [w to _,w in items] self.goods = [x for X,_ in items] self.total = SUM (weights) SELF.ACC = List (self.accumulate (weights)) def accumulate (self, Weights): #累和. Accumulate ([10,40,50])->[10,50,100] cur = 0 for w in weights: cur = cur+w yield cur< C10/>def __call__ (self): return Self.goods[bisect.bisect_right (SELF.ACC, random.uniform (0, self.total))]WR = Weightrandom ([' iphone ', ' Ten '), (' ipad ', ' Max '), (' itouch ', ')]) print WR ()
Elegant Python-weighted stochastic algorithm and its application in lottery