advent2022

Advent of Code 2022 Solutions
git clone git://bsandro.tech/advent2022
Log | Files | Refs | README | LICENSE

main.go (988B)


      1 package main
      2 
      3 import (
      4 	"fmt"
      5 	"log"
      6 	"os"
      7 )
      8 
      9 const PacketMarkerLen = 4
     10 const MessageMarkerLen = 14
     11 
     12 func main() {
     13 	if len(os.Args) > 1 {
     14 		day06(os.Args[1])
     15 	} else if len(os.Args) == 1 {
     16 		fmt.Printf("usage: %s inputfile.txt\n", os.Args[0])
     17 	} else {
     18 		fmt.Println("No input data")
     19 	}
     20 }
     21 
     22 func day06(input_file string) {
     23 	fmt.Printf("day 06 input filename: %s\n", input_file)
     24 	input, err := os.ReadFile(input_file)
     25 	if err != nil {
     26 		log.Fatal(err)
     27 	}
     28 
     29 	fmt.Println("Part 1:", checkStream(input, PacketMarkerLen))
     30 	fmt.Println("Part 2:", checkStream(input, MessageMarkerLen))
     31 }
     32 
     33 func checkStream(input []byte, size int) int {
     34 	var buf []byte
     35 	for i, b := range input {
     36 		if len(buf) > 0 {
     37 			has, pos := sliceHas(buf, b)
     38 			if has {
     39 				buf = buf[pos+1:]
     40 			} else if len(buf) == size-1 {
     41 				return i + 1
     42 			}
     43 		}
     44 		buf = append(buf, b)
     45 	}
     46 	return -1
     47 }
     48 
     49 func sliceHas(buf []byte, n byte) (bool, int) {
     50 	for i, e := range buf {
     51 		if e == n {
     52 			return true, i
     53 		}
     54 	}
     55 	return false, -1
     56 }