day 1a
This commit is contained in:
parent
c3c1fe8b3a
commit
255c191dfc
3 changed files with 74 additions and 0 deletions
39
day01/day01.go
Normal file
39
day01/day01.go
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func getCalibrationValue(input string) int {
|
||||
firstIdx := strings.IndexAny(input, "0123456789")
|
||||
lastIdx := strings.LastIndexAny(input, "0123456789")
|
||||
first := string([]rune(input)[firstIdx])
|
||||
last := string([]rune(input)[lastIdx])
|
||||
output, _ := strconv.Atoi(first + last)
|
||||
return output
|
||||
}
|
||||
|
||||
func ScanFile(file *os.File) (int, error) {
|
||||
scanner := bufio.NewScanner(file);
|
||||
sum := 0;
|
||||
for scanner.Scan() {
|
||||
sum += getCalibrationValue(scanner.Text());
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return sum, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
sum, err := ScanFile(os.Stdin)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Invalid input: %s\n", err)
|
||||
return
|
||||
}
|
||||
fmt.Println(sum)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue