day1, part2

This commit is contained in:
efim 2023-12-01 14:22:35 +00:00
parent c1794a56ec
commit bdcdc1cdb6
1 changed files with 42 additions and 3 deletions

View File

@ -5,11 +5,12 @@ import (
"fmt" "fmt"
"log" "log"
"os" "os"
"strings"
"unicode" "unicode"
) )
func Run() { func Run() {
file, err := os.Open("./day1/example.txt") file, err := os.Open("./day1/input")
if err != nil { if err != nil {
log.Print("error opening file") log.Print("error opening file")
return return
@ -22,8 +23,9 @@ func Run() {
for scanner.Scan() { for scanner.Scan() {
line := scanner.Text() line := scanner.Text()
first := getFirstDigit(line) allDigits := getDigits(line)
last := getLastDigit(line) first := allDigits[0]
last := allDigits[len(allDigits) - 1]
num := first * 10 + last num := first * 10 + last
result += num result += num
@ -32,6 +34,43 @@ func Run() {
fmt.Printf(">> day 1 result is %d", result) fmt.Printf(">> day 1 result is %d", result)
} }
func getDigits(line string) []int {
result := make([]int, 0)
for ind, ch := range line {
if unicode.IsDigit(ch) {
result = append(result, int(ch - '0'))
}
wordDigit, found := getTheDigitSubstringAt(line, ind)
if found {
result = append(result, wordDigit)
}
}
return result
}
var theDigits map[string]int = map[string]int{
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
}
func getTheDigitSubstringAt(line string, index int) (digit int, found bool) {
lineFromIndex := line[index:]
for key, num := range theDigits {
if strings.HasPrefix(lineFromIndex, key) {
return num, true
}
}
return 0, false
}
func getFirstDigit(line string) int { func getFirstDigit(line string) int {
for _, ch := range line { for _, ch := range line {
if unicode.IsDigit(ch) { if unicode.IsDigit(ch) {