advent2022

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

main.go (1106B)


      1 package main
      2 
      3 import (
      4 	"bufio"
      5 	"fmt"
      6 	"log"
      7 	"os"
      8 	"sort"
      9 	"strconv"
     10 )
     11 
     12 func main() {
     13 	if len(os.Args) > 1 {
     14 		day01(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 day01(input_file string) {
     23 	fmt.Printf("Day 01 input filename: %s\n", input_file)
     24 	input, err := os.Open(input_file)
     25 	if err != nil {
     26 		log.Fatal(err)
     27 	}
     28 	defer input.Close()
     29 	scanner := bufio.NewScanner(input)
     30 	var loads []int
     31 	cur_load := 0
     32 	for scanner.Scan() {
     33 		if len(scanner.Text()) > 0 {
     34 			load, err := strconv.Atoi(scanner.Text())
     35 			if err != nil {
     36 				log.Fatal(err)
     37 			}
     38 			cur_load += load
     39 		} else {
     40 			loads = append(loads, cur_load)
     41 			cur_load = 0
     42 		}
     43 	}
     44 	// processing last block separately since there is no \r\n there at the end
     45 	loads = append(loads, cur_load)
     46 	if err = scanner.Err(); err != nil {
     47 		log.Fatal(err)
     48 	}
     49 	sort.Ints(loads)
     50 	cnt := len(loads)
     51 	fmt.Printf("Max load: %d\n", loads[cnt-1])
     52 	if cnt > 3 {
     53 		sum3 := loads[cnt-1] + loads[cnt-2] + loads[cnt-3]
     54 		fmt.Printf("Top 3 loads sum: %d\n", sum3)
     55 	}
     56 }