package day01

import (
	"math"
	"sort"
	"strconv"
	"strings"
)

func Part1(input string) int {
	var leftList, rightList []float64
	total := 0.0
	lines := strings.Split(input, "\n")
	for _, line := range lines {
		sides := strings.Fields(line)
		leftNum, _ := strconv.ParseFloat(sides[0], 64)
		rightNum, _ := strconv.ParseFloat(sides[1], 64)
		leftList = append(leftList, leftNum)
		rightList = append(rightList, rightNum)
	}

	sort.Float64s(leftList)
	sort.Float64s(rightList)

	for i := 0; i < len(leftList); i++ {
		total += math.Abs(leftList[i] - rightList[i])
	}
	return int(total)
}

func Part2(input string) int {
	var leftList, rightList []int

	lines := strings.Split(input, "\n")
	for _, line := range lines {
		sides := strings.Fields(line)
		leftNum, _ := strconv.Atoi(sides[0])
		rightNum, _ := strconv.Atoi(sides[1])
		leftList = append(leftList, leftNum)
		rightList = append(rightList, rightNum)
	}

	counts := make(map[int]int)
	for _, num := range rightList {
		counts[num]++
	}

	similarityScore := 0
	for _, num := range leftList {
		similarityScore += num * counts[num]
	}

	return similarityScore
}
