0

Possible Duplicate:
Choosing n numbers with fixed sum

I'm developing a Bot for my Bux system in PHP. the Bot should run N times in a day and each time create variable (random) K users in a manner that sum of users in the day be fixed (M).
How can I achieve this? (Choosing Random number N times that sum of numbers be M).

Community
  • 1
  • 1
Ariyan
  • 14,760
  • 31
  • 112
  • 175
  • i don't think its duplication ??? What do you think @Snigger – Baba Apr 14 '12 at 15:22
  • @Truth: I only need first number and my choosing is discrete. My `M` changes each time I need a new number (Previous`M` - Previous`K`) – Ariyan Apr 14 '12 at 15:27
  • 1
    This PHP code would help you ..... http://codepad.viper-7.com/knf4h9 ... wrote it for you but your question was already closed – Baba Apr 14 '12 at 15:44
  • How is this not a duplicate? You want to generate N random number which has a pre-known, fixed value. This is exactly what's being asked on the linked question. – Madara's Ghost Apr 14 '12 at 15:54
  • @Snigger I also wrote up a solution. You can view it online at http://codepad.org/fcaZgyXm with accompanying blog at http://sampsonblog.com/246/n-parts-for-sum-in-php – Sampson Apr 14 '12 at 17:09

1 Answers1

1
<?php
function generate_random_sum($sum = 100)
{
    $out = array();
    while(array_sum($out) !== $sum)
    {
        $out[] = mt_rand(1, ($sum - array_sum($out)));
    }
    return $out;
}

print_r(generate_random_sum(100));

Does this help?

It will give you an array of different values totalling M in your question. Not sure how to make it create N amount of users if anyone wants to extend feel free.

Dale
  • 10,384
  • 21
  • 34