Skip to content

Commit

Permalink
Solve 2024 day 1 part B
Browse files Browse the repository at this point in the history
  • Loading branch information
arunsathiya committed Dec 22, 2024
1 parent a7de15e commit 9949664
Showing 1 changed file with 46 additions and 2 deletions.
48 changes: 46 additions & 2 deletions src/2024/day01/go/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,59 @@ func calculateDistances(input *os.File) (int, error) {
return sum, nil
}

func similarityScore(input *os.File) (int, error) {
scanner := bufio.NewScanner(input)
sum := 0
a := make([]int, 0)
b := make([]int, 0)
for scanner.Scan() {
line := scanner.Text()
first := strings.Split(line, " ")[0]
firstN, err := strconv.Atoi(first)
if err != nil {
log.Fatal(err)
}
second := strings.Split(line, " ")[1]
secondN, err := strconv.Atoi(second)
if err != nil {
log.Fatal(err)
}
a = append(a, firstN)
b = append(b, secondN)
}
sort.Slice(a, func(i, j int) bool {
return a[i] < a[j]
})
sort.Slice(b, func(i, j int) bool {
return b[i] < b[j]
})
for _, left := range a {
count := 0
for _, right := range b {
if left == right {
count++
}
}
sum += left * count
}
return sum, nil
}

func main() {
input, err := os.Open("input.txt")
if err != nil {
log.Fatal(err)
}
defer input.Close()
sum, err := calculateDistances(input)
distances, err := calculateDistances(input)
if err != nil {
log.Fatal(err)
}
input.Seek(0, 0)
similarityScore, err := similarityScore(input)
if err != nil {
log.Fatal(err)
}
fmt.Println(sum)
fmt.Println(distances)
fmt.Println(similarityScore)
}

0 comments on commit 9949664

Please sign in to comment.