Newer
Older
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package datastruct;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Matrix<T> {
private final List<List<T>> matrix;
private final int width;
private final int height;
public Matrix(int width, int height, MatrixInitializer<T> initializer) {
this.width = width;
this.height = height;
this.matrix = new ArrayList<>();
this.initializeWith(initializer);
}
public Matrix(int width, int height, T initialValue) {
this(width, height, new ConstantMatrixInitializer<>(initialValue));
}
private void initializeWith(MatrixInitializer<T> initializer) {
for (int x = 0; x < width; x++) {
List<T> row = new ArrayList<>();
this.matrix.add(row);
for (int y = 0; y < height; y++) {
row.add(initializer.initialValueAt(Coordinate.of(x,y)));
}
}
}
public T get(int x, int y) {
return this.matrix.get(x).get(y);
}
public T get(Coordinate coord) {
return this.get(coord.x(), coord.y());
}
public void set(int x, int y, T value) {
this.matrix.get(x).set(y,value);
}
public void set(Coordinate coord, T value) {
this.set(coord.x(), coord.y(), value);
}
public Iterator<T> iterator() {
Iterator<Coordinate> coordIterator = this.coordinatesIterator();
return new MatrixIterator(this, coordIterator);
}
public Iterable<Coordinate> coordinates() {
return this::coordinatesIterator;
}
private Iterator<Coordinate> coordinatesIterator() {
return new CoordinateIterator(this.width, this.height);
}
public Lens<T> at(int x, int y) {
return new Lens<T>() {
@Override
public T get() {
return Matrix.this.get(x,y);
}
@Override
public void set(T value) {
Matrix.this.set(x,y,value);
}
};
}
public Lens<T> at(Coordinate coord) {
return this.at(coord.x(), coord.y());
}
}