Presumably everyone in the new Year's time to play Rob Red envelopes very happy, today the project encountered a problem:
A total of 2000 coins, you need to randomly drop to N monsters, each of the strange drop rate of gold is less than 2000/(2 * n), N can be divisible by 2000.
After encountering this problem, I think of the new year when we all play a very happy red envelopes, at that time I think of the red envelopes how the random algorithm is implemented, which there is no sequence of loopholes exist, so that the timing of the collection to maximize their own interests. Because a lot of red envelopes in the group, are all members of the whole group of all hair, so that everyone will be to a red envelope, is not my last collar, get the most? Later this problem ran aground, did not think, these two days the project encountered the same problem, probably think about it, wrote the game in the Random drop algorithm.
def get_reward_arr(coin_sum, n): det_coin = coin_sum / n forin range(n)] 21 forin range(n): lose_coin = random.randint(0, max_lose_coin) win_index = random.randint(01) coin_arr[i] -= lose_coin coin_arr[win_index] += lose_coin return coin_arr
The program first divides the coins into n equal parts and then takes up to half of the gold coins from each of them, and at random a gold-based index is added to the gold to obtain the index.
The above is a way that I think of, and there is a common way:
def get_reward_arr(coin_sum, n): 2forin range(n)] rand_sum = reduce(lambda x, y: x + y, rand_arr) forin range(n)] return coin_arr
This is done by randomly starting out a set of arrays, and then each time you get the number of coins you get by taking a random ratio.
Results one day to see a blog about the implementation of red envelopes, in order to save space, they use a random seed must, then the random number on a certain principle, each time only records the total amount of money, the number of times to obtain, random seeds, a total of how many people. The data structure is probably: money, n, times, seed. This does not discuss how to deal with floating-point numbers, how to handle the lock problem, only to explore the random implementation mode:
def get_reward_coin(coin_sum, n, seed, times): random.seed(seed) 0 0 forin range(n): 2, n) rand_sum += ret if i == times: rand_num = ret return (rand_num * coin_sum) / rand_sum
It's very clever to save memory space by CPU time.
The above algorithm does not consider the problem of floating-point numbers, if the project involves floating-point number problems, there are different solutions for different projects.
All the test code can be accessed here. Refer to the article to access back-end technology by Tim Yang.
Monster Drop coin Caprice