This commit is contained in:
2024-12-09 01:33:33 +01:00
parent 022a451f7a
commit 2cda847908
6 changed files with 2314 additions and 0 deletions

59
Day01/optimized.go Normal file
View File

@@ -0,0 +1,59 @@
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"sort"
)
func optimized() {
// Read the file in one step
content, err := os.ReadFile("./input.json")
if err != nil {
log.Fatalf("Error when opening input.json: %v", err)
}
// Parse the JSON
var payload struct {
ListA []int `json:"list_a"`
ListB []int `json:"list_b"`
}
if err := json.Unmarshal(content, &payload); err != nil {
log.Fatalf("Error when unmarshalling input.json: %v", err)
}
// Part 1: Calculate the sum of absolute differences between sorted lists
sort.Ints(payload.ListA)
sort.Ints(payload.ListB)
sumPart1 := 0
for i := range payload.ListA {
sumPart1 += abs(payload.ListA[i] - payload.ListB[i])
}
fmt.Printf("Sum of Part 1: %d\n", sumPart1)
// Part 2: Calculate weighted sum of common elements
sumPart2 := 0
countMap := make(map[int]int)
for _, v := range payload.ListB {
countMap[v]++
}
for _, v := range payload.ListA {
if countMap[v] > 0 {
sumPart2 += v * countMap[v]
countMap[v] = 0 // Avoid double-counting
}
}
fmt.Printf("Sum of Part 2: %d\n", sumPart2)
}
// Helper function for absolute value
func abs(x int) int {
if x < 0 {
return -x
}
return x
}