-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathRectangleSpliterator.java
More file actions
executable file
·68 lines (50 loc) · 1.89 KB
/
RectangleSpliterator.java
File metadata and controls
executable file
·68 lines (50 loc) · 1.89 KB
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
package spliterators.part1.exercise;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.IntConsumer;
public class RectangleSpliterator extends Spliterators.AbstractIntSpliterator {
private final int innerLength;
private final int[][] array;
private int startInclusive;
private int endExclusive;
public RectangleSpliterator(int[][] array) {
this(array, 0, array.length * array[0].length);
}
private RectangleSpliterator(int[][] array, int startInclusive, int endExclusive) {
super(Long.MAX_VALUE, Spliterator.IMMUTABLE | Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL);
innerLength = array.length == 0 ? 0 : array[0].length;
this.array = array;
this.startInclusive = startInclusive;
this.endExclusive = endExclusive;
}
@Override
public OfInt trySplit() {
int length = (int) estimateSize();
if (length < 5) {
return null;
}
int mid = startInclusive + length / 2;
RectangleSpliterator rectangleSpliterator = new RectangleSpliterator(array, startInclusive, mid);
startInclusive = mid;
return rectangleSpliterator;
}
@Override
public long estimateSize() {
return (long) (endExclusive - startInclusive);
}
@Override
public boolean tryAdvance(IntConsumer action) {
int i = startInclusive / innerLength;
int j = startInclusive - i*innerLength;
action.accept(array[i][j]);
return true;
}
@Override
public void forEachRemaining(IntConsumer action) {
for (int i = startInclusive; i < endExclusive; i++) {
int ii = i / innerLength;
int jj = i - ii*innerLength;
action.accept(array[ii][jj]);
}
}
}