# Paste: sma without subgroups

Author: glguy factor Sat, 11 Apr 2009 06:22:16
Plain Text |
```! http://phildawes.net/blog/2009/03/30/factor-makes-you-write-better-code/

IN: sma

USING: kernel sequences math arrays math.ranges math.order ;

: partial-sums ( seq -- newseq )
0 [ + ] accumulate
swap suffix 1 tail ;

: differences ( seq seq -- newseq )
[ - ] 2map ;

: prepad ( seq n elt -- newseq )
<array> prepend ;

: sliding-partial-sums ( seq n -- newseq )
dupd 0 prepad differences partial-sums ;

: plateau ( len n -- seq )
[ min [1,b] ]
[ - 0 max ]
[ nip <array> ] 2tri append ;

: sma ( seq n -- newseq )
[ sliding-partial-sums ]
[ [ length ] dip plateau ] 2bi
[ / ] 2map ;```

## Annotation: revised

Author: glguy factor Sun, 12 Apr 2009 06:49:51
Plain Text |
```! http://phildawes.net/blog/2009/03/30/factor-makes-you-write-better-code/

IN: sma

USING: arrays kernel math math.order math.ranges math.vectors sequences ;

: partial-sums ( seq -- newseq )
0 [ + ] accumulate swap suffix rest ;

: sliding-partial-sums ( seq n -- newseq )
dupd 0 <array> prepend
v- partial-sums ;

: plateau ( len n -- seq )
[ min [1,b] ]
[ - 0 max ]
[ nip <array> ] 2tri append ;

: sma ( seq n -- newseq )
[ sliding-partial-sums ]
[ [ length ] dip plateau ] 2bi v/ ;```

## Annotation: further revised

Author: glguy factor Sun, 12 Apr 2009 07:05:04
Plain Text |
```! http://phildawes.net/blog/2009/03/30/factor-makes-you-write-better-code/

IN: sma

USING: arrays kernel math math.order math.ranges math.vectors sequences ;

: partial-sums ( seq -- newseq )
0 [ + ] accumulate swap suffix rest ;

: sliding-partial-sums ( seq n -- newseq )
dupd 0 <array> prepend v- partial-sums ;

: plateau ( len n -- seq )
[ min [1,b] ] [ [ append ] padding ] 2bi ;

: sma ( seq n -- newseq )
[ sliding-partial-sums ]
[ [ length ] dip plateau ] 2bi v/ ;```