small pixel drawing of a pufferfish aoc

2024/day1/puzzle2.go

package main

import (
	"bufio"
	"fmt"
	"os"
	"slices"
	"strconv"
	"strings"
)

func main() {
	var left []int
	var right []int

	file, _ := os.Open("input1.txt")
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		fields := strings.Split(line, "   ")

		l, _ := strconv.Atoi(fields[0])
		left = append(left, l)
		r, _ := strconv.Atoi(fields[1])
		right = append(right, r)

		slices.Sort(left)
		slices.Sort(right)
	}

	var total int
	for i := range left {
		d := similarity(left[i], right)
		total += d
	}
	fmt.Println(total)
}

// calculate similarity score based on
// how many times n appears in the list
func similarity(n int, list []int) int {
	count := 0
	for _, l := range list {
		if n == l {
			count++
		}
	}

	return n * count
}