I was a friend who asked me to write a method in excel: In the case of 36 numbers between 1 and 36, 5 were randomly selected to make the sum of 100: I am not very familiar with excel, so I try to write a method using php: Imagine:If the five numbers fluctuate around 20, and the fluctuation values offset each other, then the random number can be easily obtained. Ideas:A_random + B _random + a_offset + c_random + B _offset + d_random + c_offset + e_random Where a_offset is the fluctuation value of a_random and 20 in the middle, it indicates a_random + a_offset = 20, similarly, B _random + B _offset = 20, etc. Then (a_random + a_offset) + (B _random + B _offset) + (c_random + c_offset) + d_random + e_random = 60 + d_random + e_random; The last number e_random is not random. it is obtained from 100-60-d_random. you only need to randomly output d_random and then judge whether it meets the requirements. If you have a better method, please follow me and tell me, thank you!
- // Parameter settings
- $ Total = 100;
- $ Min_num = 1;
- $ Max_num = 36;
- $ Times = 5;
- $ Average = $ total/$ times;
- $ Now = 0;
- For ($ I = 0; $ I <$ times; $ I ++)
- {
- $ Off = 0;
- $ Tmp = 0;
- If ($ I = $ times-1)
- {
- $ Tmp = $ total-$ now;
- If ($ tmp> $ max_num | $ tmp <0)
- {
- $ Off = $ now = 0;
- $ I = 0;
- // Echo "$ tmp |"; // data that does not meet the requirements
- Unset ($ num );
- $ Tmp = rand ($ min_num, $ max_num );
- $ Off = $ tmp-$ average;
- $ Now = $ now + $ tmp;
- $ Num [] = $ tmp;
- Continue;
- }
- Else
- {
- $ Num [] = $ tmp;
- Break;
- }
- }
- If ($ off = 0)
- {
- $ Tmp = rand ($ min_num, $ max_num );
- }
- Else
- {
- $ Tmp = rand ($ min_num-$ off, $ max_num-$ off );
- $ Tmp = ($ tmp + $ off );
- }
- $ Off = $ tmp-$ average;
- $ Now = $ now + $ tmp;
- $ Num [] = $ tmp;
- }
- // Test
- $ Con = '';
- Foreach ($ num as $ val)
- {
- $ Total_my = $ total_my + $ val;
- Echo $ con. "$ val ";
- $ Con = "+ ";
- }
- Echo '='. $ total_my;
- Exit;
- ?>
|