1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 package com.unitesk.atp.treedl;
32
33 /***
34 * Iteratable index of {@link Matrix}.
35 * Index can be converted to integer to get element of matrix stored in linear array.
36 *
37 * @author <A href="mailto:demakov@ispras.ru">Alexey Demakov</A>
38 * @version $Id: Index.java,v 1.4 2006/03/13 12:27:16 all-x Exp $
39 */
40 public class Index
41 {
42 /***
43 * Create index of start position for the given matrix.
44 *
45 * @param matrix
46 */
47 public Index( Matrix matrix )
48 {
49 this( matrix, new int[matrix.getDim()] );
50 this.index = 0;
51 }
52
53 /***
54 * Create index of the given position for the given matrix.
55 *
56 * @param matrix
57 * @param indexArray
58 */
59 public Index( Matrix matrix, int[] indexArray )
60 {
61 this.matrix = matrix;
62 if( matrix.getDim() != indexArray.length )
63 {
64 throw new IllegalArgumentException
65 ( "wrong dimention: " + matrix.getDim() + "!=" + indexArray.length );
66 }
67 this.indexArray = indexArray;
68 }
69
70 /***
71 * Get linear index.
72 *
73 * @return
74 */
75 public int getIndex()
76 {
77 if( index == -1 ) update();
78 return index;
79 }
80
81 /***
82 * Get i-th coordinate of index.
83 *
84 * @param i
85 * @return
86 */
87 public int getIndex( int i )
88 {
89 return indexArray[i];
90 }
91
92 /***
93 * Set i-th coordinate of index.
94 *
95 * @param i
96 * @param v
97 */
98 public void setIndex( int i, int v )
99 {
100 indexArray[i] = v;
101 index = -1;
102 }
103
104 private void update()
105 {
106 index = 0;
107 for( int i = 0; i < indexArray.length; i++ )
108 {
109 index *= matrix.getSize( i );
110 index += indexArray[i];
111 }
112 }
113
114 /***
115 * Move index to start position.
116 */
117 public void init()
118 {
119 for( int i = 0; i < matrix.getDim(); i++ )
120 {
121 indexArray[i] = 0;
122 }
123 index = 0;
124 }
125
126 /***
127 * Check if index points to an element of the matrix.
128 */
129 public boolean has()
130 {
131 return index < matrix.getLength();
132 }
133
134 /***
135 * Move index to the next element of the matrix.
136 */
137 public void next()
138 {
139 if( index == -1 ) update();
140 index++;
141
142 for( int i = matrix.getDim() - 1; i >= 0; i-- )
143 {
144 if( ++indexArray[i] < matrix.getSize( i ) ) break;
145 indexArray[i] = 0;
146 }
147 }
148
149 /***
150 * Convert index to String.
151 */
152 public String toString()
153 {
154 StringBuffer sb = new StringBuffer();
155 for( int i = 0; i < matrix.getDim(); i++ )
156 {
157 if( i > 0 ) sb.append( ',' );
158 sb.append( indexArray[i] );
159 }
160 return sb.toString();
161 }
162
163 private Matrix matrix;
164 private int[] indexArray;
165
166 private int index = -1;
167 }