1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package net.sf.zel.instr.var;
21
22 import net.sf.zel.instr.*;
23 import net.sf.zel.vm.*;
24 import java.util.*;
25 import net.sf.zel.nr.OperableDouble;
26 import net.sf.zel.nr.OperableNumber;
27
28
29 public final class AVG extends Instruction
30 {
31
32
33
34
35 public static final Instruction instance = new AVG();
36
37 private static final long serialVersionUID = 4115104411671388053L;
38
39 private AVG(){};
40
41
42
43
44
45
46 public void execute(ExecutionContext context) throws ZExecutionException
47 {
48 final MatchIterator iterator = new MatchIterator((String) context.popSyncStackVal());
49 context.stack.pop();
50 Averager stuff = new Averager();
51 iterator.iterate(stuff, context.memContext);
52 context.stack.push(stuff.getAverage());
53 context.ip++;
54 }
55
56 private static final class Averager implements MatchIterator.DoStuff
57 {
58
59
60
61
62 private transient double sum = 0;
63
64
65
66 private transient double cnt = 0;
67
68 public OperableDouble getAverage()
69 {
70 if (cnt == 0)
71 {
72 return null;
73 } else
74 {
75 return new OperableDouble(sum/cnt);
76 }
77 }
78
79 public void execute(Object obj, List context)
80 {
81 if (obj instanceof OperableNumber)
82 {
83 sum += ((Number) obj).doubleValue();
84 cnt++;
85 }
86 }
87 }
88 }