Skip to content

Instantly share code, notes, and snippets.

@lfaoro
Created December 3, 2024 08:10
Show Gist options
  • Save lfaoro/459432c3f9c056f75fadec03078ad939 to your computer and use it in GitHub Desktop.
Save lfaoro/459432c3f9c056f75fadec03078ad939 to your computer and use it in GitHub Desktop.
advent of code day1 (go)
package main
import (
"bufio"
"log"
"os"
"sort"
"strconv"
"strings"
)
func main() {
inputs, err := os.Open("inputs")
if err != nil {
log.Println(err)
return
}
defer inputs.Close()
var lst1, lst2 []int
scan := bufio.NewScanner(inputs)
for scan.Scan() {
line := scan.Text()
parts := strings.Fields(line)
if len(parts) < 2 {
log.Println("mismatched input")
return
}
for i, v := range parts {
vv, _ := strconv.Atoi(v)
if i == 0 {
lst1 = append(lst1, vv)
} else {
lst2 = append(lst2, vv)
}
}
}
sort.Ints(lst1)
sort.Ints(lst2)
if len(lst1) != len(lst2) {
log.Println("mismatched slices")
return
}
var total int
for i := 0; i < len(lst1); i++ {
a, b := lst1[i], lst2[i]
if a > b {
total += a - b
} else {
total += b - a
}
// log.Println(total, a, b)
}
log.Println(total)
}
@lfaoro
Copy link
Author

lfaoro commented Dec 3, 2024

part2

	var total int
	for i := 0; i < len(lst1); i++ {
		var count int
		for j := 0; j < len(lst2); j++ {
			a, b := lst1[i], lst2[j]
			if a == b {
				count++
			}
		}
		total += lst1[i] * count
	}
	log.Println(total)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment