We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi! This should be easy but I'm stuck :-/
I have the values 3,4 and 5
I have an array where I put these values randomly. The array stops accepting values when the total sum of values hits 50. I'm close, but sometimes the total sum is 48 or 49 because in some cases the partial sum is 48 or 49 and my lowest value is 3 to fill it. I need that (whatever the distribution of values is) the sum is always 50.
How to do this in an elegant way?
Answers
Well with an if check if you're at 48/49
If so, insert the last value as a new value lastValue=50-sumUpToNow;
So lastValue is 1 or 2 if that's ok.
Alternativly, when you add a last value 3/4/5 you end up with a val >50 - let's call it surplus
Now say
surplus = sumUpToNow-50;
This should give 1 or 2
Now for loop over the array or randomly pick a 5 and substract surplus from it
So you modify an old entry to make the entire sum be 50
When you calculate the next random number (3, 4 or 5) only add it to the array IF it makes the new sum <= 47 OR == 50 in other words there will either be room for another number or you have reached your target.
Yeah, I thought of that at first but I can't find the optimal solution (in this case the sum of the array varies, even checking for surplus..
Note that an elegant solution would not use a
for
loop to populate the array rather it would use awhile
loop and ado-while
loop. ;)Please enlighten me (the 'elegant' part was referring to something that didn't use some long and painstaking manual check). I know this is a mess, just trying to find something that works first, then I'll do some cleaning. (we'll see about that, all my code tends to look like a geological dump of patches and duct tape).
The for-loop is useful if you know the number of times the loop-body-code is to be executed. This is not the case because although you know you want the sum to equal 50 you don't know how many numbers will end up in the array.
In the code below
sum50
method populates the array with the numbers 3, 4 or 5 until the total is 50. It does not use a for-loop.A sample run output
Thanks @quark ,really helpful