View Javadoc

1   /*
2    * Copyright (c) 2001, Zoltan Farkas All Rights Reserved.
3    *
4    * This library is free software; you can redistribute it and/or
5    * modify it under the terms of the GNU Lesser General Public
6    * License as published by the Free Software Foundation; either
7    * version 2.1 of the License, or (at your option) any later version.
8    *
9    * This library is distributed in the hope that it will be useful,
10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   * GNU General Public License for more details.
13   *
14   * You should have received a copy of the GNU Lesser General Public
15   * License along with this program; if not, write to the Free Software
16   * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
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       * instance
34       */
35      public static final Instruction instance = new AVG();
36      
37      private static final long serialVersionUID = 4115104411671388053L;
38  
39      private AVG(){};
40  
41      /**
42       * RAVG Instruction microcode
43       * @param context ExecutionContext
44       * @throws ZExecutionException
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           * summ variable
61           */
62          private transient double sum = 0;
63          /**
64           * count variable
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  }