forked from exercism/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlowerFieldBoard.java
More file actions
75 lines (54 loc) · 2.61 KB
/
Copy pathFlowerFieldBoard.java
File metadata and controls
75 lines (54 loc) · 2.61 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
69
70
71
72
73
74
75
import java.util.ArrayList;
import java.util.List;
final class FlowerFieldBoard {
private static final char FLOWER_CHAR = '*';
private static final char SPACE_CHAR = ' ';
private final List<String> rawRepresentation;
private final int numberOfRows;
private final int numberOfColumns;
FlowerFieldBoard(final List<String> rawRepresentation) {
this.rawRepresentation = rawRepresentation;
this.numberOfRows = rawRepresentation.size();
this.numberOfColumns = rawRepresentation.isEmpty() ? 0 : rawRepresentation.get(0).length();
}
List<String> withNumbers() {
final List<String> result = new ArrayList<>();
for (int rowNumber = 0; rowNumber < numberOfRows; rowNumber++) {
result.add(getRowWithNumbers(rowNumber));
}
return result;
}
private String getRowWithNumbers(final int rowNumber) {
StringBuilder result = new StringBuilder(numberOfColumns);
for (int columnNumber = 0; columnNumber < numberOfColumns; columnNumber++) {
result.append(getCellNumber(rowNumber, columnNumber));
}
return result.toString();
}
private char getCellNumber(final int rowNumber, final int columnNumber) {
// If (rowNumber, columnNumber) is a flower, we're done.
if (rawRepresentation.get(rowNumber).charAt(columnNumber) == FLOWER_CHAR) {
return FLOWER_CHAR;
}
final int flowerCount = computeFlowerCountAround(rowNumber, columnNumber);
// If computed count is positive, add it to the annotated row. Otherwise, add a blank space.
return flowerCount > 0 ? Character.forDigit(flowerCount, 10) : SPACE_CHAR;
}
private int computeFlowerCountAround(final int rowNumber, final int columnNumber) {
int result = 0;
// Compute row and column ranges to inspect (respecting board edges).
final int minRowToInspect = Math.max(rowNumber - 1, 0);
final int maxRowToInspect = Math.min(rowNumber + 1, numberOfRows - 1);
final int minColToInspect = Math.max(columnNumber - 1, 0);
final int maxColToInspect = Math.min(columnNumber + 1, numberOfColumns - 1);
// Count flowers in the cells surrounding (row, col).
for (int rowToInspect = minRowToInspect; rowToInspect <= maxRowToInspect; rowToInspect++) {
for (int colToInspect = minColToInspect; colToInspect <= maxColToInspect; colToInspect++) {
if (rawRepresentation.get(rowToInspect).charAt(colToInspect) == FLOWER_CHAR) {
result += 1;
}
}
}
return result;
}
}