Shop OBEX P1 Docs P2 Docs Learn Events
Summing Values in an Array — Parallax Forums

Summing Values in an Array

coryco2coryco2 Posts: 107
edited 2014-10-09 17:59 in Propeller 1
What would be the most compact, efficient SPIN code to use for summing the values in a variable array whose values change frequently?

I would like something better than Sum := ArrayItem[0] + ArrayItem[1] +...ArrayItem[n].

Any suggestions?

Comments

  • Duane DegnDuane Degn Posts: 10,588
    edited 2014-10-09 13:38
    One way is:
    sum := 0
      repeat index from 0 to MAX_INDEX
         sum += arrayItem[index]
    
  • ElectrodudeElectrodude Posts: 1,658
    edited 2014-10-09 16:21
    How often is the sum needed relative to how often values change?

    If you need the sum only rarely, do what Duane Degn said. But if you need the sum every time you change any single value, update the sum every time you change a value by subtracting out the old value of the element you're about to overwrite and then adding in the new value, with something like this:
    VAR
    
      long  sum
      long  values[16]
    
    PRI changevalue(i, x)
    
      sum += x-values[i]
      values[i] := x
    
      return sum
    
  • coryco2coryco2 Posts: 107
    edited 2014-10-09 17:59
    Thanks; much appreciated!
Sign In or Register to comment.