small pixel drawing of a pufferfish aoc

2024/day2/puzzle1.go

package main

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

func main() {
	file, _ := os.Open("input")
	defer file.Close()

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

		numbas := make([]int, len(level))
		for i, s := range level {
			numbas[i], _ = strconv.Atoi(s)
		}

		increases, err := seqIncreases(numbas)
		if err != nil {
			continue
		}
		decreases, err := seqDecreases(numbas)
		if err != nil {
			continue
		}

		if increases > 0 && decreases > 0 {
			continue
		}

		safeLevels += 1
	}

	fmt.Println(safeLevels)
}

// calculate sequential increases in da numbas
func seqIncreases(numbas []int) (int, error) {
	count := 0
	for i := range numbas {
		// stop if we're about to go out-of-bounds with
		// our naive comparison stuff
		if i+1 == len(numbas) {
			break
		}

		if difference(numbas[i], numbas[i+1]) > 3 {
			return -1, errors.New("difference greater than 3")
		}

		if difference(numbas[i], numbas[i+1]) == 0 {
			return -1, errors.New("same numbers detected")
		}

		if numbas[i] < numbas[i+1] {
			count += 1
		}
	}
	return count, nil
}

// calculate decreases increases in da numbas
func seqDecreases(numbas []int) (int, error) {
	count := 0
	for i := range numbas {
		if i+1 == len(numbas) {
			break
		}

		if difference(numbas[i], numbas[i+1]) > 3 {
			return -1, errors.New("difference greater than 3")
		}

		if difference(numbas[i], numbas[i+1]) == 0 {
			return -1, errors.New("same numbers detected")
		}

		if numbas[i] > numbas[i+1] {
			count += 1
		}
	}
	return count, nil
}

func difference(i1 int, i2 int) int {
	if i1 > i2 {
		return i1 - i2
	}
	return i2 - i1
}