|
1 | 1 | package warriors
|
2 | 2 |
|
| 3 | +import ( |
| 4 | + "strings" |
| 5 | +) |
| 6 | + |
3 | 7 | // Count calculates warriors on the image
|
4 | 8 | func Count(image string) int {
|
5 |
| - return 0 |
| 9 | + count := 1 |
| 10 | + parsed := parse(image) |
| 11 | + |
| 12 | + for j, row := range parsed { |
| 13 | + for i, col := range row { |
| 14 | + switch { |
| 15 | + case col > 1: //We've already seen part of this Byte Warrior |
| 16 | + paint(col, j, i, parsed) |
| 17 | + case col == 1: //This is a new Byte Warrior |
| 18 | + count++ |
| 19 | + paint(count, j, i, parsed) |
| 20 | + } |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + return count - 1 |
| 25 | + |
| 26 | +} |
| 27 | + |
| 28 | +func parse(image string) [][]int { |
| 29 | + rows := strings.Split(image, "\n") |
| 30 | + parsed := make([][]int, len(rows)+1) |
| 31 | + for row, line := range rows { |
| 32 | + parsed[row] = make([]int, len(line)) |
| 33 | + for col, r := range line { |
| 34 | + parsed[row][col] = int(r - '0') |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + return parsed |
| 39 | +} |
| 40 | + |
| 41 | +func paint(color, pointJ, pointI int, image [][]int) { |
| 42 | + /* |
| 43 | + Need to paint unvisited pixels |
| 44 | + - - - |
| 45 | + - X X |
| 46 | + X X X |
| 47 | + */ |
| 48 | + for j := 0; j <= 1; j++ { |
| 49 | + for i := -j; i <= 1; i++ { |
| 50 | + toPaintJ := pointJ + j |
| 51 | + toPaintI := pointI + i |
| 52 | + |
| 53 | + inBounds := toPaintI >= 0 && toPaintJ < len(image) && toPaintI < len(image[toPaintJ]) |
| 54 | + |
| 55 | + if inBounds && image[toPaintJ][toPaintI] == 1 { |
| 56 | + image[toPaintJ][toPaintI] = color |
| 57 | + } |
| 58 | + } |
| 59 | + } |
6 | 60 | }
|
0 commit comments