I currently have an array of randomly generated numbers ranging between 0.5
and 1
:
local ArrayOfRandomlyGeneratedNumbers = {
[1] = 0.56756654;
[2] = 0.56756767;
[3] = 0.76576576;
[4] = ...
}
I have a function that counts the total of all of the values within the array:
local function CalculateTotalAmount(Array)
local TotalAmount = 0;
for Index, Value in ipairs(Array) do
TotalAmount += Value;
end
return TotalAmount;
end
I need a way of proportionally scaling all numbers within the array so that the total equals a specific number, however the initial limits (0.5 < Value < 1)
must be adhered to.
For example, say the target total is 2.5
, but the calculated total of my array is 2.1
:
local Array = { -- Total: (0.5 + 0.7 + 0.9) = 2.1
[1] = 0.5;
[2] = 0.7;
[3] = 0.9;
}
local TargetTotalAmount = 2.5;
Logically you could apply a flat scaling factor of 2.5 / 2.1 = 1.19
to all values, however in doing this it would take my 0.9
value to 1.07
, which is over the upper limit of 1
. And if I hard-cap it at 1
, I would need a way to further scale the other values to account for the 0.07
extra that was taken out. This is the part that I need assistance with.
Is there a good way of solving this problem efficiently?
TL;DR: Scale values in an array to total a specific number, without letting any individual value exceed numerical limits.
user28774945 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.