advent-of-code

Perserverance, or the lack thereof

git clone git://git.shimmy1996.com/advent-of-code.git

main.go (1546B)

    1 package main
    2 
    3 import (
    4 	"bufio"
    5 	"fmt"
    6 	"os"
    7 	"strconv"
    8 )
    9 
   10 func readInput(filename string) (res []int64) {
   11 	file, _ := os.Open(filename)
   12 	defer file.Close()
   13 
   14 	scanner := bufio.NewScanner(file)
   15 	for scanner.Scan() {
   16 		num, _ := strconv.ParseInt(scanner.Text(), 10, 64)
   17 		res = append(res, num)
   18 	}
   19 	return
   20 }
   21 
   22 func main() {
   23 	input := readInput("./input.txt")
   24 	// 14144619
   25 	fmt.Println(part1(input))
   26 	// 1766397
   27 	fmt.Println(part2(input))
   28 }
   29 
   30 func part1(input []int64) (int64, bool) {
   31 	preambleLen := 25
   32 	window := make(map[int64]int)
   33 	for i := 0; i < preambleLen; i++ {
   34 		window[input[i]] += 1
   35 	}
   36 	for i := preambleLen; i < len(input); i++ {
   37 		found := false
   38 		for j := i - preambleLen; j < i; j++ {
   39 			if (input[i] != 2*input[j] && window[input[i]-input[j]] >= 1) ||
   40 				(input[i] == 2*input[j] && window[input[j]] >= 2) {
   41 				found = true
   42 				break
   43 			}
   44 		}
   45 		if !found {
   46 			return input[i], true
   47 		}
   48 		window[input[i-preambleLen]] -= 1
   49 		window[input[i]] += 1
   50 	}
   51 	return 0, false
   52 }
   53 
   54 func minMax(input []int64) (min int64, max int64) {
   55 	min, max = input[0], input[0]
   56 	for _, v := range input {
   57 		if v < min {
   58 			min = v
   59 		}
   60 		if v > max {
   61 			max = v
   62 		}
   63 	}
   64 	return
   65 }
   66 
   67 func part2(input []int64) (int64, bool) {
   68 	target, _ := part1(input)
   69 	cumsum := []int64{0}
   70 	for _, v := range input {
   71 		cumsum = append(cumsum, cumsum[len(cumsum)-1]+v)
   72 	}
   73 	for i := 0; i < len(cumsum); i++ {
   74 		for j := i + 1; j < len(cumsum); j++ {
   75 			if cumsum[j]-cumsum[i] == target {
   76 				min, max := minMax(input[i:j])
   77 				return min + max, true
   78 			}
   79 		}
   80 	}
   81 	return 0, false
   82 }