Skip to content

Instantly share code, notes, and snippets.

@Micrified
Created December 5, 2023 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Micrified/e6b002743c63c3525c659557dbfa0e5e to your computer and use it in GitHub Desktop.
Save Micrified/e6b002743c63c3525c659557dbfa0e5e to your computer and use it in GitHub Desktop.
Day 3; Advent of Code
package main
import (
"fmt"
"bufio"
"os"
"strings"
"unicode"
)
// Return true if rune at the coordinate is
// adjacent to a special character
func isPart (i, j int, m [][]rune) bool {
isSpecial := func (c rune) bool {
return !(unicode.IsDigit(c) || '.' == c)
}
return isSpecial(m[i-1][j-1]) ||
isSpecial(m[i-1][j]) ||
isSpecial(m[i-1][j+1]) ||
isSpecial(m[i][j-1]) ||
isSpecial(m[i][j+1]) ||
isSpecial(m[i+1][j-1]) ||
isSpecial(m[i+1][j]) ||
isSpecial(m[i+1][j+1])
}
func partSum (m [][]rune) int {
sum := 0
for i := 1; i < (len(m)-1); i++ {
r := m[i]
part, n := false, 0
for j := 1; j < (len(r)-1); j++ {
if unicode.IsDigit(r[j]) {
n = n*10+(r[j]-'0')
part = part || isPart(i,j,m)
} else {
if part {
sum += n
}
n = 0
part = false
}
}
}
return sum
}
func main() {
s, n := bufio.NewScanner(os.Stdin), 0
input := make([][]rune)
repl := func (c rune, n int) []rune {
r := []rune{}
for i := 0; i < n; i++ {
r = append(r, c)
}
return r
}
// Snarf
for s.Scan() {
input = append(input, []rune(s.Text()))
}
// Format
padding = repl('.', len(input[0]) + 2)
m := make([][]rune)
m = append(m,padding)
for _, r := range input {
pr := make([]rune)
pr = append(pr, '.')
pr = append(pr, r...)
pr = append(pr, '.')
}
m = append(m,padding)
// Process
fmt.Printf("%d\n", partSum(m))
// Scan in the first three lines, always keep three
// .........
// ...343...
// .........
// Optionally pad the first line and last line
// Scan left to right and interpret numbers. For
// each character in the number, check with the
// following scan pattern
// ...+++...
// ...+1+...
// ...+++...
// if any such special character is found, then this
// number (when scan complete) is to be added to the
// sum
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment