0

The title is slightly misleading: What I am trying to is a little bit more complicated, but I don't know how to describe it in a title.

I have two sequences (vectors, arrays, lists) p and q of numbers. I sum all of the numbers in p except the first element, then perform a test. If the fails, I replace the first element of p with the first element of q, and start over with the second element: Sum all elements of p except the second one (including the new element copied from q). If the test fails the second time, replace the second element in p with the second element in q, and do it again with the third element. The test always succeeds on some element. Pseudocode:

i = 0 if test(sum_except p i) then exit loop else p[i] := q[i], and run again with i+1 

This means that if I have 1000 elements, I sum 999 of them, and then the next time through I sum 998 of those plus a new element, and so on. As the process goes on, I am also summing more and more elements from q rather than from the original p, but I will have summed most of them, previously, as well. So at each step, I'm summing a bunch of numbers that I had already added together. This seems inefficient, but I have not figured out a more sensible way to write this.

In case it matters, what the test does is check whether the sum of the values in p except the element at i, plus the value of q at i, is greater or equal to than 1 (or is less than or equal to 1--there are two variants). i.e.:

(sum_except p i) + q[i] > 1 

This all happens inside an inner loop, and the sequence length will probably be between 500 and 5000, although larger numbers are possible.

(My code actually is in OCaml, fwiw.)

1 Answer 1

3

Calculate the sum of all numbers at the start (henceforth referred to as sum). sum_except p i is then equivalent to sum - p[i].

When you update an item in the list, update the sum as well so that you do not have to recalculate it by looping through each element in p every time.

// Remove old value sum := sum - p[i] p[i] := q[i] // Add new value sum := sum + p[i] 

Since you will be modifying at most one value in the list at a time, you can simply update the sum manually to reflect the change instead of summing all elements in the list again, which makes the loop body run in constant time.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I didn't see that. It produces a significant speedup.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.