day 01
This commit is contained in:
1000
01/input.txt
Normal file
1000
01/input.txt
Normal file
File diff suppressed because it is too large
Load Diff
54
01/main.go
Normal file
54
01/main.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
var (
|
||||
inputFile = flag.String("input", "input.txt", "input filename")
|
||||
reLine = regexp.MustCompile(`(?m)^(\d+)\s+(\d+)$`)
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
input, err := os.ReadFile(*inputFile)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
var leftList, rightList []int
|
||||
for _, match := range reLine.FindAllStringSubmatch(string(input), -1) {
|
||||
leftNumber, err := strconv.Atoi(match[1])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
rightNumber, err := strconv.Atoi(match[2])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
leftList = append(leftList, leftNumber)
|
||||
rightList = append(rightList, rightNumber)
|
||||
}
|
||||
|
||||
sort.SliceStable(leftList, func(i, j int) bool {
|
||||
return leftList[i] < leftList[j]
|
||||
})
|
||||
sort.SliceStable(rightList, func(i, j int) bool {
|
||||
return rightList[i] < rightList[j]
|
||||
})
|
||||
|
||||
totalDistance := 0
|
||||
for i := 0; i < len(leftList); i++ {
|
||||
totalDistance += int(math.Abs(float64(leftList[i] - rightList[i])))
|
||||
}
|
||||
|
||||
fmt.Println(totalDistance)
|
||||
}
|
Reference in New Issue
Block a user