RosettaCodeData/Task/Averages-Simple-moving-average/NetRexx/averages-simple-moving-aver...

64 lines
1.7 KiB
Plaintext

/* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 20
class RAvgSimpleMoving public
properties private
window = java.util.Queue
period
sum
properties constant
exMsg = 'Period must be a positive integer'
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method RAvgSimpleMoving(period_) public
if \period_.datatype('w') then signal RuntimeException(exMsg)
if period_ <= 0 then signal RuntimeException(exMsg)
window = LinkedList()
period = period_
sum = 0
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method newNum(num) public
sum = sum + num
window.add(num)
if window.size() > period then do
rmv = (Rexx window.remove())
sum = sum - rmv
end
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method getAvg() public returns Rexx
if window.isEmpty() then do
avg = 0
end
else do
avg = sum / window.size()
end
return avg
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method run_samples(args = String[]) public static
testData = [Rexx 1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
windowSizes = [Rexx 3, 5]
loop windSize over windowSizes
ma = RAvgSimpleMoving(windSize)
loop xVal over testData
ma.newNum(xVal)
say 'Next number =' xVal.right(5)', SMA =' ma.getAvg().format(10, 9)
end xVal
say
end windSize
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method main(args = String[]) public static
run_samples(args)
return