Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a specified amount of random values that all equal up to a specified number in PHP?

Tags:

php

random

For example, say I enter '10' for the amount of values, and '10000' as a total amount.

The script would need to randomize 10 different numbers that all equal up to 10000. No more, no less.

But it needs to be dynamic, as well. As in, sometimes I might enter '5' or '6' or even '99' for the amount of values, and any number (up to a billion or even higher) as the total amount.

How would I go about doing this?

EDIT: I should also mention that all numbers need to be a positive integer

like image 691
Rob Avatar asked Sep 12 '10 21:09

Rob


2 Answers

The correct answer here is unbelievably simple.

Just imagine a white line, let's say 1000 units long.

You want to divide the line in to ten parts, using red marks.

VERY SIMPLY, CHOOSE NINE RANDOM NUMBERS and put a red paint mark at each of those points.

It's just that simple. You're done!

Thus, the algorithm is:

(1) pick nine random numbers between 0 and 1000 (2) put the nine numbers, a zero, and a 1000, in an array (3) sort the array (4) using subtraction get the ten "distances" between array values

You're done.

(Obviously if you want to have no zeros in your final set, in part (1) simply rechoose another random number if you get a collision.)

Ideally as programmers, we can "see" visual algorithms like this in our heads -- try to think visually whatever we do!


Footnote - for any non-programmers reading this, just to be clear pls note that this is like "the first thing you ever learn when studying computer science!" i.e. I do not get any credit for this, I just typed in the answer since I stumbled on the page. No kudos to me!

Just for the record another common approach (depending on the desired outcome, whether you're dealing with real or whole numbers, and other constraints) is also very "ah hah!" elegant. All you do is this: get 10 random numbers. Add them up. Remarkably simply, just: multiply or divide them all by some number, so that, the total is the desired total! It's that easy!

like image 170
Fattie Avatar answered Sep 29 '22 12:09

Fattie


maybe something like this:

set max amount remaining to the target number

loop for 1 to the number of values you want - 1

get a random number from 0 to the max amount remaining

set new max amount remaining to old max amount remaining minus the current random number

repeat loop

you will end up with a 'remainder' so the last number is determined by whatever is left over to make up the original total.

like image 43
Randy Avatar answered Sep 29 '22 12:09

Randy