KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tonbeller > jpivot > util > CubeIndexIterator


1 /*
2  * ====================================================================
3  * This software is subject to the terms of the Common Public License
4  * Agreement, available at the following URL:
5  * http://www.opensource.org/licenses/cpl.html .
6  * Copyright (C) 2003-2004 TONBELLER AG.
7  * All Rights Reserved.
8  * You must accept the terms of that agreement to use this software.
9  * ====================================================================
10  *
11  *
12  */

13 package com.tonbeller.jpivot.util;
14
15 /**
16  * generate array of indexes for an n-dimensional qube
17  * basically "n" nested loops
18  * for (i1 =0; i1 < n1 ; i1++ )
19  * for (i2 =0; i2 < n2 ; i2++ )
20  * ...
21  * for (im =0; im < nm ; im++ )
22  */

23 public class CubeIndexIterator {
24   int[] ni;
25   int[] iCurrent;
26   boolean firstFast;
27   int nDim;
28
29   /**
30    * c'tor
31    * @param ni - array of max indexes for dimensions
32    * @param firstFast , first index runs fastest if true
33    */

34   public CubeIndexIterator(int[] ni, boolean firstFast) {
35     this.ni = ni;
36     this.firstFast = firstFast;
37     nDim = ni.length;
38     iCurrent = new int[nDim];
39     reset();
40   }
41
42   /**
43    * @return next index array, null if done
44    */

45   public int[] next() {
46     if (nDim == 0)
47       return null;
48     if (firstFast) {
49       ++iCurrent[0];
50       for (int i = 0; i < nDim - 1; i++) {
51         if (iCurrent[i] > ni[i]) {
52           ++iCurrent[i + 1];
53           iCurrent[i] = 0;
54         }
55       }
56       if (iCurrent[nDim - 1] > ni[nDim - 1])
57         return null;
58     } else {
59       ++iCurrent[nDim - 1];
60       for (int i = nDim - 1; i > 0; i--) {
61         if (iCurrent[i] > ni[i]) {
62           ++iCurrent[i - 1];
63           iCurrent[i] = 0;
64         }
65       }
66       if (iCurrent[0] > ni[0])
67         return null;
68     }
69     return iCurrent;
70   }
71
72   /**
73    * reset
74    */

75   public void reset() {
76     if (nDim == 0)
77       return;
78     for (int i = 0; i < nDim; i++) {
79       if (!firstFast && i == nDim - 1)
80         iCurrent[i] = -1;
81       else if (firstFast && i == 0)
82         iCurrent[i] = -1;
83       else
84         iCurrent[i] = 0;
85     }
86   }
87 } // CubeIndexIterator
88
Popular Tags