54 lines
789 B
Go
54 lines
789 B
Go
package dayone
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"unicode"
|
|
)
|
|
|
|
func Run() {
|
|
file, err := os.Open("./day1/example.txt")
|
|
if err != nil {
|
|
log.Print("error opening file")
|
|
return
|
|
}
|
|
defer file.Close()
|
|
|
|
scanner := bufio.NewScanner(file)
|
|
|
|
result := 0
|
|
|
|
for scanner.Scan() {
|
|
line := scanner.Text()
|
|
first := getFirstDigit(line)
|
|
last := getLastDigit(line)
|
|
|
|
num := first * 10 + last
|
|
result += num
|
|
}
|
|
|
|
fmt.Printf(">> day 1 result is %d", result)
|
|
}
|
|
|
|
func getFirstDigit(line string) int {
|
|
for _, ch := range line {
|
|
if unicode.IsDigit(ch) {
|
|
return int(ch - '0')
|
|
}
|
|
}
|
|
return 0
|
|
}
|
|
|
|
func getLastDigit(line string) int {
|
|
for i := len(line) - 1; i >= 0; i-- {
|
|
simbols := []rune(line)
|
|
ch := simbols[i]
|
|
if unicode.IsDigit(ch) {
|
|
return int(ch - '0')
|
|
}
|
|
}
|
|
return 0
|
|
}
|