advent2022

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

main.go (1406B)


      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 		day10(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 day10(input_file string) {
     21 	fmt.Printf("day 10 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 	cycle := 0
     29 	x := 1
     30 	sum := 0
     31 	for scanner.Scan() {
     32 		in := scanner.Text()
     33 		if in == "noop" {
     34 			drawPixel(cycle, x)
     35 			cycle++
     36 			if checkCycle(cycle) {
     37 				sum += cycle * x
     38 			}
     39 		} else {
     40 			var ins string
     41 			var dx int
     42 			found, err := fmt.Sscanf(in, "%s %d", &ins, &dx)
     43 			if found != 2 || err != nil {
     44 				log.Fatal(err)
     45 			}
     46 			drawPixel(cycle, x)
     47 			cycle++
     48 			if checkCycle(cycle) {
     49 				sum += cycle * x
     50 			}
     51 			drawPixel(cycle, x)
     52 			cycle++
     53 			if checkCycle(cycle) {
     54 				sum += cycle * x
     55 			}
     56 			x += dx
     57 		}
     58 	}
     59 	if err = scanner.Err(); err != nil {
     60 		log.Fatal(err)
     61 	}
     62 	fmt.Print("\n")
     63 	fmt.Println("sum:", sum)
     64 }
     65 
     66 func checkCycle(cycle int) bool {
     67 	return cycle == 20 ||
     68 		cycle == 60 ||
     69 		cycle == 100 ||
     70 		cycle == 140 ||
     71 		cycle == 180 ||
     72 		cycle == 220
     73 }
     74 
     75 func drawPixel(cycle, x int) {
     76 	xs := cycle % 40
     77 	if xs == 0 {
     78 		fmt.Print("\n")
     79 	}
     80 	if xs-1 == x || xs == x || xs+1 == x {
     81 		fmt.Print("#")
     82 	} else {
     83 		fmt.Print(" ")
     84 	}
     85 }