Skip to content

Instantly share code, notes, and snippets.

@reconbot
Created December 4, 2023 17:42
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 reconbot/203b11b60ff4e33b869acb5b4e1cfba2 to your computer and use it in GitHub Desktop.
Save reconbot/203b11b60ff4e33b869acb5b4e1cfba2 to your computer and use it in GitHub Desktop.
a broken program for solving day 1
package main
import (
"bufio"
"os"
"regexp"
"strconv"
"strings"
)
func main() {
data, err := os.Open("day1.txt")
if err != nil {
panic(err)
}
scanner := bufio.NewScanner(data)
calibration := 0
for scanner.Scan() {
line := scanner.Text()
first_number := ""
last_number := ""
// part 2
// scan for the first matching named number and replace it, repeat until there's no more matches
re := regexp.MustCompile(`(one|two|three|four|five|six|seven|eight|nine)`)
for match := re.FindString(line); match != ""; match = re.FindString(line) {
valueMap := make(map[string]rune)
valueMap["one"] = '1'
valueMap["two"] = '2'
valueMap["three"] = '3'
valueMap["four"] = '4'
valueMap["five"] = '5'
valueMap["six"] = '6'
valueMap["seven"] = '7'
valueMap["eight"] = '8'
valueMap["nine"] = '9'
if _, ok := valueMap[match]; !ok {
panic(line + match)
}
line = strings.Replace(line, match, string(valueMap[match]), 1)
}
for _, c := range line {
if _, err := strconv.Atoi(string(c)); err == nil {
if first_number == "" {
first_number = string(c)
}
last_number = string(c)
}
}
number, err := strconv.Atoi(first_number + last_number)
if err != nil {
panic(err)
}
calibration += number
}
if err := scanner.Err(); err != nil {
panic(err)
}
println("Calibration", calibration)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment