Skip to content

Instantly share code, notes, and snippets.

@Kirth
Created December 17, 2024 21:40
Show Gist options
  • Save Kirth/563cddb9a3ce580f3fd9548e9d9a50e2 to your computer and use it in GitHub Desktop.
Save Kirth/563cddb9a3ce580f3fd9548e9d9a50e2 to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
"strings"
)
func readInputs(filename string, processLine func(a, b int)) error {
input, err := os.Open(filename)
if err != nil {
panic(fmt.Sprintln("Error opening input: ", err))
}
defer input.Close()
scanner := bufio.NewScanner(input)
for scanner.Scan() {
line := scanner.Text()
values := strings.Fields(line)
if len(values) != 2 {
panic("Line did not contain two values")
}
a, errA := strconv.Atoi(values[0])
b, errB := strconv.Atoi(values[1])
if errA != nil || errB != nil {
return fmt.Errorf("invalid integer input: %v, %v", errA, errB)
}
processLine(a, b)
}
return nil
}
func listCount(input []int, x int) int {
count := 0
for _, v := range input {
if v == x {
count += 1
}
}
return count
}
func main() {
var left, right []int
err := readInputs("input1.txt", func(a, b int) {
left = append(left, a)
right = append(right, b)
})
if err != nil {
panic(fmt.Sprintf("Error reading input %s", err))
}
sort.Ints(left)
sort.Ints(right)
// part 1
// result := 0
// for i := 0; i < len(left); i++ {
// diff := int(math.Abs(float64(left[i] - right[i])))
// result += diff
// }
// part 2
result := 0
for _, v := range left {
result += v * listCount(right, v) // SIMILARITY SCORE
}
fmt.Println(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment