Let’s say I have an array float array[7] = {0.1, 0.2, 0.4, 0.8, 0.4, 0.2, 0.1};
Essentially, I want to multiply each element in the array by a scalar so that the total sum of all the elements in the array is equal to a desired value, lets say 10.
My first thought was to run through a loop, multiply each element by the same scalar, add them up, and check to see if the total is less than desired value. If so, I would run the loop again with a slightly larger scalar and continue this until the desired value was hit. This seems like a pretty bad approach as it is unclear how many times you will need to run the loop before the threshold is reached. The actual array I am using is 100+ elements, and runtime is important for my application.
Is there some sort of math I could apply to this problem so that I could figure out the proper scalar to use without having to use the approach I outlined above? I would love a solution that would require only one loop to run through the array and multiply by the correct scalar. I apologize if this is a poor or too vague of question, but I haven’t been able to come up with a good solution.
I have already implemented a version of what I described in my initial approach in c++, but it runs slow and the sum of the elements does not add up perfectly to the certain value I am trying to reach.