awelgorithms

The write pointer is the logical length

Updated

Return w. Callers loop i < w, not i < n. a.length stays n. a[w..] is leftover, not part of the answer.

What to focus on

Physical n and logical w can disagree. Reading past w mixes junk into the result.

Worked examples

len 2 of 4

a = [1, 9, 0, 9], w=2 after compact zeros
  1. loop i<2
  2. sees 1 then 9
  3. index 2 is leftover 0

Result: logical length 2

len 2 drop 1s

a = [4, 9, 9, 1], w=2 after keep ≠ 1
  1. sum of a[0..w) is 13
  2. sum of all 4 slots is 23

Result: use w, not n

len 3

a = [4, 1, 9], w=3 keep all
  1. w==n
  2. every slot counts

Result: logical length 3

Try it

Write sumLogical(a, w). a is an array of integers. w is the logical length with 0 ≤ w ≤ n. Loop i < w, not i < n. Return the sum of a[0..w). Do not print. For leftover [1, 9, 0, 9] w=2 the sum is 10. For [4, 9, 9, 1] w=2 the sum is 13. For [4, 1, 9] w=3 the sum is 14.

a is nonempty. w is the logical length with 0 ≤ w ≤ n.