Among 36 numbers between 1-36, 5 are randomly selected so that the sum is 100

WBOY
Release: 2016-07-25 09:09:34
Original
1295 people have browsed it

Originally, a friend asked me to help write a method in excel: randomly select 5 of the 36 numbers between 1-36 so that the sum is 100:

I am not very good at using excel, so I try to write a method in php:

Imagine: If the five numbers all fluctuate around 20, and the fluctuation values ​​cancel each other out, then the random number will be easy to find.

Idea: 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 the middle value 20, then it means a_random+a_offset=20, similarly b_random+b_offset=20, etc.

Then finally (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 derived from 100-60-d_random. Then you only need to randomly find d_random and then judge whether it meets the requirements.
If you have a better method, you can tell me in the thread, thank you!

  1. //Parameter settings
  2. $total=100;
  3. $min_num=1;
  4. $max_num=36;
  5. $times=5;
  6. $average=$total/$times;
  7. $ now=0;
  8. for($i=0;$i<$times;$i++)
  9. {
  10. $off=0;
  11. $tmp=0;
  12. if($i==$times-1)
  13. {
  14. $tmp=$total-$now;
  15. if($tmp>$max_num||$tmp<0)
  16. {
  17. $off=$now=0;
  18. $i=0;
  19. // echo "$tmp|" ;//Data that does not meet the requirements
  20. unset($num);
  21. $tmp=rand($min_num,$max_num);
  22. $off=$tmp-$average;
  23. $now=$now+$tmp;
  24. $num []=$tmp;
  25. continue;
  26. }
  27. else
  28. {
  29. $num[]=$tmp;
  30. break;
  31. }
  32. }
  33. if($off==0)
  34. {
  35. $tmp=rand($ min_num,$max_num);
  36. }
  37. else
  38. {
  39. $tmp=rand($min_num-$off,$max_num-$off);
  40. $tmp=($tmp+$off);
  41. }
  42. $off=$tmp -$average;
  43. $now=$now+$tmp;
  44. $num[]=$tmp;
  45. }
  46. // Test
  47. $con='';
  48. foreach($num as $val)
  49. {
  50. $total_my =$total_my+$val;
  51. echo $con."$val";
  52. $con="+";
  53. }
  54. echo '='.$total_my;
  55. exit;
  56. ?>
Copy code


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!