~rootmos/AoC

15838ef7d17fde87fb3ecc9d84141648849c30a2 — Gustav Behm 4 months ago 8ef546e
Add solution to AoC 2023 #01b
2 files changed, 48 insertions(+), 2 deletions(-)

M 2023/01.go
A 2023/01b.example
M 2023/01.go => 2023/01.go +41 -2
@@ 4,9 4,10 @@ import (
	"log"
	"os"
	"bufio"
	"strings"
)

func partA(fn string) {
func getLines(fn string) (ls []string) {
	f, err := os.Open(fn)
	if err != nil {
		log.Fatal(err)


@@ 14,13 15,48 @@ func partA(fn string) {
	defer f.Close()

	s := bufio.NewScanner(f)
	sum := 0
	for i := 0; s.Scan(); i++ {
		l := s.Text()
		ls = append(ls, l)
		//log.Printf("%s:%d: %s", fn, i, l)
	}
	return
}

func partA(fn string) {
	sum := 0
	for _, l := range getLines(fn) {
		var ds []int
		for j := 0; j < len(l); j++ {
			if '0' <= l[j] && l[j] <= '9' {
				ds = append(ds, int(l[j] - '0'))
			}
		}
		switch len(ds) {
		case 0:
		case 1: sum += ds[0]*10 + ds[0]
		default: sum += ds[0]*10 + ds[len(ds)-1]
		}
	}
	log.Printf("%s: %v", fn, sum)
}

func partB(fn string) {
	sum := 0
	digits := []string{ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }
	for _, l := range getLines(fn) {
		var ds []int
		for j := 0; j < len(l); j++ {
			if '0' <= l[j] && l[j] <= '9' {
				ds = append(ds, int(l[j] - '0'))
				continue
			}

			for d, s := range digits {
				if strings.HasPrefix(l[j:], s) {
					ds = append(ds, d+1)
					continue
				}
			}
		}
		switch len(ds) {


@@ 35,4 71,7 @@ func partA(fn string) {
func main() {
	partA("01.example") // 142
	partA("01.input") // 54573

	partB("01b.example") // 281
	partB("01.input") // 54591
}

A 2023/01b.example => 2023/01b.example +7 -0
@@ 0,0 1,7 @@
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen