add 2024/day1
This commit is contained in:
parent
b435fb5f63
commit
9cc8248821
4 changed files with 1098 additions and 0 deletions
1000
2024/01/input
Normal file
1000
2024/01/input
Normal file
File diff suppressed because it is too large
Load diff
56
2024/01/main.go
Normal file
56
2024/01/main.go
Normal file
|
@ -0,0 +1,56 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"aoc2024/helper"
|
||||
"fmt"
|
||||
"sort"
|
||||
)
|
||||
|
||||
var list_a, list_b []int
|
||||
|
||||
func main() {
|
||||
list_a, list_b = helper.ReadLinesTwoIntSlices()
|
||||
|
||||
// part 1
|
||||
distance := list_distance(list_a, list_b)
|
||||
fmt.Printf("Distance: %v\n", distance)
|
||||
|
||||
// part 2
|
||||
similarity := list_similarity(list_a, list_b)
|
||||
fmt.Printf("Similarity: %v\n", similarity)
|
||||
}
|
||||
|
||||
func list_distance(list_a []int, list_b []int) (dist int) {
|
||||
sort.Ints(list_a)
|
||||
sort.Ints(list_b)
|
||||
|
||||
for i := range list_a {
|
||||
dist += abs(list_a[i] - list_b[i])
|
||||
}
|
||||
return dist
|
||||
}
|
||||
|
||||
func abs(x int) int {
|
||||
if x < 0 {
|
||||
return -x
|
||||
}
|
||||
|
||||
return x
|
||||
}
|
||||
|
||||
func list_similarity(list_a []int, list_b []int) (sim int) {
|
||||
for _, val := range list_a {
|
||||
valcount := countIntInList(list_b, val)
|
||||
sim += valcount * val
|
||||
}
|
||||
return sim
|
||||
}
|
||||
|
||||
func countIntInList(lst []int, i int) (count int) {
|
||||
for _, val := range lst {
|
||||
if val == i {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
3
2024/go.mod
Normal file
3
2024/go.mod
Normal file
|
@ -0,0 +1,3 @@
|
|||
module aoc2024
|
||||
|
||||
go 1.23.3
|
39
2024/helper/input.go
Normal file
39
2024/helper/input.go
Normal file
|
@ -0,0 +1,39 @@
|
|||
package helper
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const INPUT_FILE = "input"
|
||||
|
||||
func GetLines() *bufio.Scanner {
|
||||
wd, err := os.Getwd()
|
||||
filePath := filepath.Join(wd, INPUT_FILE)
|
||||
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
return bufio.NewScanner(file)
|
||||
}
|
||||
|
||||
func ReadLinesTwoIntSlices() (list_a []int, list_b []int) {
|
||||
scanner := GetLines()
|
||||
for scanner.Scan() {
|
||||
parts := strings.Fields(scanner.Text())
|
||||
|
||||
value_a, _ := strconv.Atoi(parts[0])
|
||||
value_b, _ := strconv.Atoi(parts[1])
|
||||
|
||||
list_a = append(list_a, value_a)
|
||||
list_b = append(list_b, value_b)
|
||||
}
|
||||
|
||||
return list_a, list_b
|
||||
}
|
Loading…
Reference in a new issue