-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathTriangularArray.java
50 lines (39 loc) · 915 Bytes
/
TriangularArray.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package ds_003_arrays;
public class TriangularArray<T> {
private int numRows;
private T[] values;
@SuppressWarnings("unchecked")
public TriangularArray(int numRows) {
this.numRows = numRows;
values = (T[])new Object[numRows * (numRows-1) / 2];
}
private int mapRowAndCol(int row, int col) {
if(row < col) {
int temp = col;
col = row;
row = temp;
}
return row*(row-1)/2 + col;
}
public void set(T value, int row, int col) {
values[mapRowAndCol(row, col)] = value;
}
public T get(int row, int col) {
return values[mapRowAndCol(row, col)];
}
public int size() {
return values.length;
}
public void printArray() {
for(int i = 0; i < numRows; i++) {
for(int j = 0; j < numRows; j++) {
if(i == j) {
System.out.printf(". ");
} else {
System.out.printf("%s ", values[mapRowAndCol(i, j)]);
}
}
System.out.print("\n");
}
}
}