I have an array of integers and a number n
. I want to sum the elements of the array and return the index where the sum passes n
, as efficiently as possible.
For example, assume:
theString = "6-7-7-10-7-6"
theNumber = 33
expected result: 5
This does the trick but not very efficiently: (and error prone; will check for errors when I've found the best solution)
Public Function getIndexFromSum(theString As String, theNumber As Integer) As Integer
Dim theSides As Variant
Dim sum As Integer
Dim index As Integer
theSides = Split(theString, "-")
While sum <= theNumber
sum = sum + theSides(index)
index = index + 1
Wend
getIndexFromSum = index
End Function
I haven't been able to describe this to google succinctly enough to get any meaningful results, and searching for any combination of the keywords involved produces links to tons of unrelated stuff. I'm sure this problem will have been encountered before (and likely has a smart solution out there somewhere), but I haven't been able to find any sites that can help.
Any help/advice would be very much appreciated!
EDIT - more info
1) theString
will always be stored in the format "x-x-x".
2) theNumber
will always be smaller than or equal to the sum of the numbers in theString
.
3) The length of theString
will be short - usually between 2 and 10 numbers, each less than 100.
4) The function will be called with small inputs, but many times. Low overhead is top priority.
theString
always stored in a String format "x-x-x"? Where does it come from? 2. Rough idea how bigtheString
is? Rough idea how bigtheNumber
generally will be? 3. How often and in what circumstances is this function going to be used? 4. Have you measured how long the function takes to run? Can you provide some data of calculations? You really need to provide more content along with your question to get a better performing algorithm. \$\endgroup\$ – user28366 Feb 25 '14 at 11:09