advent2022

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

main.go (1051B)


      1 package main
      2 
      3 import (
      4 	"bufio"
      5 	"fmt"
      6 	"log"
      7 	"os"
      8 )
      9 
     10 func main() {
     11 	if len(os.Args) > 1 {
     12 		day04(os.Args[1])
     13 	} else if len(os.Args) == 1 {
     14 		fmt.Printf("usage: %s inputfile.txt\n", os.Args[0])
     15 	} else {
     16 		fmt.Println("No input data")
     17 	}
     18 }
     19 
     20 func day04(input_file string) {
     21 	fmt.Printf("day 04 input filename: %s\n", input_file)
     22 	input, err := os.Open(input_file)
     23 	if err != nil {
     24 		log.Fatal(err)
     25 	}
     26 	defer input.Close()
     27 	scanner := bufio.NewScanner(input)
     28 	overlaps1 := 0
     29 	overlaps2 := 0
     30 	for scanner.Scan() {
     31 		in := scanner.Text()
     32 		var p1, p2 [2]int
     33 		parsed, err := fmt.Sscanf(in, "%d-%d,%d-%d", &p1[0], &p1[1], &p2[0], &p2[1])
     34 		if err != nil || parsed != 4 {
     35 			log.Fatal("Invalid input string", in, err)
     36 		}
     37 		if (p1[0] >= p2[0] && p1[1] <= p2[1]) || (p2[0] >= p1[0] && p2[1] <= p1[1]) {
     38 			overlaps1++
     39 		}
     40 		if (p1[0] >= p2[0] && p1[0] <= p2[1]) || (p2[0] >= p1[0] && p2[0] <= p1[1]) {
     41 			overlaps2++
     42 		}
     43 	}
     44 	if err = scanner.Err(); err != nil {
     45 		log.Fatal(err)
     46 	}
     47 
     48 	fmt.Println("Part 1:", overlaps1)
     49 	fmt.Println("Part 2:", overlaps2)
     50 }