commit 93b22b966fd2a01eb109b7f8791568a77965be45 (patch)
parent 400bdb83f1d1105fd4fe195d21f256b80ec82f1a
Author: Alex Karle <alex@alexkarle.com>
Date: Fri, 29 Nov 2024 02:23:23 +0100
2023: Add day 1 in go
Prepping for 2024!
Diffstat:
5 files changed, 131 insertions(+), 0 deletions(-)
diff --git a/2023/.gitignore b/2023/.gitignore
@@ -0,0 +1,3 @@
+# these are usually binaries if no extension
+1
+2
diff --git a/2023/01/1.go b/2023/01/1.go
@@ -0,0 +1,42 @@
+package main
+
+import (
+ "bufio"
+ "fmt"
+ "log"
+ "os"
+ "unicode"
+)
+
+func main() {
+ f, err := os.Open("input.txt")
+ if err != nil {
+ log.Fatal(err)
+ }
+ defer f.Close()
+
+ sum := 0
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ line := scanner.Text()
+ first := -1
+ last := -1
+ for _, c := range line {
+ if unicode.IsNumber(c) {
+ n := int(c - '0')
+ if first == -1 {
+ first = n
+ last = n
+ } else {
+ last = n
+ }
+ }
+ }
+ sum += 10*first + last
+ }
+ fmt.Println(sum)
+
+ if err := scanner.Err(); err != nil {
+ log.Fatal(err)
+ }
+}
diff --git a/2023/01/2.go b/2023/01/2.go
@@ -0,0 +1,76 @@
+package main
+
+import (
+ "bufio"
+ "fmt"
+ "log"
+ "os"
+ "regexp"
+ "strconv"
+)
+
+func getNum(s string) int {
+ switch s {
+ case "one":
+ return 1
+ case "two":
+ return 2
+ case "three":
+ return 3
+ case "four":
+ return 4
+ case "five":
+ return 5
+ case "six":
+ return 6
+ case "seven":
+ return 7
+ case "eight":
+ return 8
+ case "nine":
+ return 9
+ default:
+ n, err := strconv.Atoi(s)
+ if err != nil {
+ return -1
+ }
+ return n
+ }
+}
+
+func parseLine(line string) (int, int) {
+ firstRe := regexp.MustCompile("([0-9]|one|two|three|four|five|six|seven|eight|nine)")
+ lastRe := regexp.MustCompile(".*([0-9]|one|two|three|four|five|six|seven|eight|nine)")
+ first := getNum(firstRe.FindStringSubmatch(line)[1])
+ last := getNum(lastRe.FindStringSubmatch(line)[1])
+
+ return first, last
+}
+
+func main() {
+ fname := "input.txt"
+ if len(os.Args) > 1 {
+ fname = os.Args[1]
+ }
+ f, err := os.Open(fname)
+ if err != nil {
+ log.Fatal(err)
+ }
+ defer f.Close()
+
+ sum := 0
+ scanner := bufio.NewScanner(f)
+ for scanner.Scan() {
+ line := scanner.Text()
+ first, last := parseLine(line)
+ if os.Getenv("DEBUG") != "" {
+ fmt.Println(10*first + last)
+ }
+ sum += 10*first + last
+ }
+ fmt.Println(sum)
+
+ if err := scanner.Err(); err != nil {
+ log.Fatal(err)
+ }
+}
diff --git a/2023/01/go.mod b/2023/01/go.mod
@@ -0,0 +1,3 @@
+module alexkarle.com/aoc-2023-d1
+
+go 1.23.1
diff --git a/2023/01/sample.txt b/2023/01/sample.txt
@@ -0,0 +1,7 @@
+two1nine
+eightwothree
+abcone2threexyz
+xtwone3four
+4nineeightseven2
+zoneight234
+7pqrstsixteen