add aoc2024 day 1 solns
This commit is contained in:
parent
55259e5568
commit
7cf7aac751
5 changed files with 105 additions and 0 deletions
1
go/.gitignore
vendored
Normal file
1
go/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
input/*.txt
|
55
go/cmd/part1/main.go
Normal file
55
go/cmd/part1/main.go
Normal file
|
@ -0,0 +1,55 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
left := []int64{};
|
||||
right := []int64{};
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
|
||||
for {
|
||||
raw, _, _ := reader.ReadLine()
|
||||
line := string(raw)
|
||||
if strings.Trim(line, " ") == "" {
|
||||
break
|
||||
}
|
||||
|
||||
values := strings.Split(line, " ")
|
||||
|
||||
l, _ := strconv.ParseInt(values[0], 10, 64)
|
||||
r, _ := strconv.ParseInt(values[1], 10, 64)
|
||||
|
||||
left = append(left, l)
|
||||
right = append(right, r)
|
||||
}
|
||||
|
||||
ans := part1(&left, &right)
|
||||
|
||||
fmt.Println("", ans)
|
||||
}
|
||||
|
||||
func part1(left *[]int64, right *[]int64) int64 {
|
||||
slices.SortFunc(*left, func (a, b int64) int { return int(a - b); });
|
||||
slices.SortFunc(*right, func (a, b int64) int { return int(a - b); });
|
||||
|
||||
var sum int64 = 0
|
||||
|
||||
sz := len(*left)
|
||||
|
||||
for i := 0; i < sz; i++ {
|
||||
diff := (*left)[i] - (*right)[i]
|
||||
if diff < 0 {
|
||||
diff = diff * -1
|
||||
}
|
||||
sum += diff
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
46
go/cmd/part2/main.go
Normal file
46
go/cmd/part2/main.go
Normal file
|
@ -0,0 +1,46 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
left := map[int64]int64{};
|
||||
right := map[int64]int64{};
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
|
||||
for {
|
||||
raw, _, _ := reader.ReadLine()
|
||||
line := string(raw)
|
||||
if strings.Trim(line, " ") == "" {
|
||||
break
|
||||
}
|
||||
|
||||
values := strings.Split(line, " ")
|
||||
|
||||
l, _ := strconv.ParseInt(values[0], 10, 64)
|
||||
r, _ := strconv.ParseInt(values[1], 10, 64)
|
||||
|
||||
left[l] = left[l] + 1
|
||||
right[r] = right[r] + 1
|
||||
}
|
||||
|
||||
ans := part2(left, right)
|
||||
|
||||
fmt.Println("", ans)
|
||||
}
|
||||
|
||||
func part2(left map[int64]int64, right map[int64]int64) int64 {
|
||||
var sum int64 = 0
|
||||
|
||||
for key, l_count := range left {
|
||||
count := right[key]
|
||||
sum += l_count * count * key
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
3
go/go.mod
Normal file
3
go/go.mod
Normal file
|
@ -0,0 +1,3 @@
|
|||
module aoc_2024/day1
|
||||
|
||||
go 1.23.4
|
0
go/input/.keep
Normal file
0
go/input/.keep
Normal file
Loading…
Add table
Reference in a new issue