Get `n` random values between 2 numbers having average `x`

前端 未结 5 642
你的背包
你的背包 2021-01-28 12:21

I want to get n random numbers(e.g n=16)(whole numbers) between 1 to 5(including both) so that average is x.

x can be any value between (1, 1.5, 2, 2.5, 3,

5条回答
  •  佛祖请我去吃肉
    2021-01-28 12:42

    Edit: I have re-written this to avoid having to call the function recursively.

     $max || $min * $count > $total || $max * $count < $total)
        {
          return FALSE;
        }
    
        // Get the specified number of random integers
        for ($i = 0; $i < $count; ++$i)
        {
    
          // Get a random number within the given range
          $rand = mt_rand($min, $max);
    
          // As a default do not continue
          $cont = FALSE;
    
          // Check to see if the random number is acceptable and if not change it until it is
          while (!$cont)
          {
    
            // If the number is too high then decrease it by one
            if (($total - $rand) - (($count - 1 - $i) * $min) < 0)
            {
              --$rand;
            }
    
            // Otherwise if the number is too low then increase it by one
            elseif (($total - $rand) - (($count - 1 - $i) * $max) > 0)
            {
              ++$rand;
            }
    
            // Otherwise we can continue
            else
            {
              $cont = TRUE;
            }
    
          }
    
          // Store the number and minus it from the total
          $total -= $result[] = $rand;
    
        }
    
        // Return the result
        return $result;
    
      }
    
      // Output an array of random numbers
      print_r(getRandomNumbers());
    

提交回复
热议问题