Question: How do I do indexed addition

I am attempting to add the contents of a variable based on the contents of another. There should be some way to do this without looping. I get errors when trying to do this with seq. I seem to not understand evaluation...

How do I do this?

restart;
## generate some values like in the real app
roll:=rand(1..9):
N := sort([seq(seq(10*(2+jdx)+roll(),jdx=1..5),idx=1..10)]):
V := 10*seq(roll()+10*trunc(N[idx]/10),idx=1..nops(N)):

## generate index for sum. This groups the values for sum
sumidx := [seq(floor(N[idx]/10)-2,idx=1..nops(N))];

## create and zero sum variable
S := 0 *~convert(convert(trunc~(N/10),set),list);

## calc sum and display it - This works
for idx to nops(sumidx) do
    S[ sumidx[idx] ] += V[idx]:
end do:
S;

## error because sumidx[idx] is not evaluated ?????
S := 0 *~convert(convert(trunc~(N/10),set),list):
seq('S'[ sumidx[idx] ] += V[idx], idx=1..nops(N));
S;

## This works 'S' delays evaluation and sumidx[idx] is evaluated in
## the function call
f := proc( A, B )
    A += B:
end proc:
## zero sum variable
S := 0 *~convert(convert(trunc~(N/10),set),list):
seq(f('S'[ sumidx[idx] ], V[idx]),idx=1..nops(N)):
S;
 

Please Wait...