|
| 1 | +package day03 |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "math" |
| 6 | + "strconv" |
| 7 | + "strings" |
| 8 | +) |
| 9 | + |
| 10 | +type Solver struct{} |
| 11 | + |
| 12 | +func (d Solver) Part1(input string) string { |
| 13 | + num, _ := strconv.Atoi(strings.TrimSpace(input)) |
| 14 | + return fmt.Sprintf("%d", d.calculateDistance(num)) |
| 15 | +} |
| 16 | + |
| 17 | +func (d Solver) Part2(input string) string { |
| 18 | + num, _ := strconv.Atoi(strings.TrimSpace(input)) |
| 19 | + return fmt.Sprintf("%d", d.calculateStressedDistance(num)) |
| 20 | +} |
| 21 | + |
| 22 | +func (d Solver) abs(x int) int { |
| 23 | + if x < 0 { |
| 24 | + return -x |
| 25 | + } |
| 26 | + return x |
| 27 | +} |
| 28 | + |
| 29 | +func (d Solver) calculateDistance(n int) int { |
| 30 | + if n == 1 { |
| 31 | + return 0 |
| 32 | + } |
| 33 | + ring := int(math.Ceil((math.Sqrt(float64(n)) - 1) / 2)) |
| 34 | + side := 2*ring + 1 |
| 35 | + maxNum := side * side |
| 36 | + sideLen := side - 1 |
| 37 | + midPoints := make([]int, 4) |
| 38 | + for i := 0; i < 4; i++ { |
| 39 | + midPoints[i] = maxNum - sideLen/2 - i*sideLen |
| 40 | + } |
| 41 | + minDist := d.abs(n - midPoints[0]) |
| 42 | + for _, midPoint := range midPoints { |
| 43 | + dist := d.abs(n - midPoint) |
| 44 | + if dist < minDist { |
| 45 | + minDist = dist |
| 46 | + } |
| 47 | + } |
| 48 | + return ring + minDist |
| 49 | +} |
| 50 | + |
| 51 | +func (d Solver) calculateStressedDistance(inputNum int) int { |
| 52 | + directions := [][2]int{{0, 1}, {-1, 0}, {0, -1}, {1, 0}} |
| 53 | + allNeighborDiffs := [][2]int{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}} |
| 54 | + coordsToNeighborSum := map[[2]int]int{{0, 0}: 1, {0, 1}: 1} |
| 55 | + directionIndex := 0 |
| 56 | + row, col := 0, 1 |
| 57 | + for { |
| 58 | + leftDiff := directions[(directionIndex+1)%4] |
| 59 | + leftCoord := [2]int{row + leftDiff[0], col + leftDiff[1]} |
| 60 | + if _, ok := coordsToNeighborSum[leftCoord]; !ok { |
| 61 | + directionIndex = (directionIndex + 1) % 4 |
| 62 | + } |
| 63 | + diff := directions[directionIndex] |
| 64 | + row += diff[0] |
| 65 | + col += diff[1] |
| 66 | + next := [2]int{row, col} |
| 67 | + var sum int |
| 68 | + for _, d := range allNeighborDiffs { |
| 69 | + sum += coordsToNeighborSum[[2]int{row + d[0], col + d[1]}] |
| 70 | + } |
| 71 | + if sum > inputNum { |
| 72 | + return sum |
| 73 | + } |
| 74 | + coordsToNeighborSum[next] = sum |
| 75 | + } |
| 76 | +} |
0 commit comments