Created
February 23, 2024 15:34
-
-
Save olisolomons/b2ab6c4ec8bc1686400c26935e2cef70 to your computer and use it in GitHub Desktop.
Advent of Code 2023 day 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "bufio" | |
| "fmt" | |
| "os" | |
| "regexp" | |
| "strconv" | |
| ) | |
| var lineRe = regexp.MustCompile(`\d|one|two|three|four|five|six|seven|eight|nine`) | |
| var numbers = map[string]uint64{ | |
| "one": 1, | |
| "two": 2, | |
| "three": 3, | |
| "four": 4, | |
| "five": 5, | |
| "six": 6, | |
| "seven": 7, | |
| "eight": 8, | |
| "nine": 9, | |
| } | |
| func parseNumber(digitStr string) uint64 { | |
| digit, exists := numbers[digitStr] | |
| if !exists { | |
| digit, _ = strconv.ParseUint(digitStr, 10, 8) | |
| } | |
| return digit | |
| } | |
| func lineToNumber(line string) uint64 { | |
| first := lineRe.FindStringIndex(line) | |
| last := first | |
| for last[0]+1 < len(line) { | |
| match := lineRe.FindStringIndex(line[last[0]+1:]) | |
| if match == nil { | |
| break | |
| } | |
| last = []int{match[0] + last[0] + 1, match[1] + last[0] + 1} | |
| } | |
| digit1 := parseNumber(line[first[0]:first[1]]) | |
| digit2 := parseNumber(line[last[0]:last[1]]) | |
| return 10*digit1 + digit2 | |
| } | |
| func main() { | |
| if len(os.Args) != 2 { | |
| fmt.Println("Expected input file name to be passed in as an argument") | |
| return | |
| } | |
| readFile, err := os.Open(os.Args[1]) | |
| if err != nil { | |
| fmt.Println(err) | |
| } | |
| fileScanner := bufio.NewScanner(readFile) | |
| fileScanner.Split(bufio.ScanLines) | |
| sum := uint64(0) | |
| for fileScanner.Scan() { | |
| sum += lineToNumber(fileScanner.Text()) | |
| } | |
| fmt.Println(sum) | |
| readFile.Close() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment