github.com/frodejac/aoc-2022@v0.0.0-20221213081734-037c741b1c89/internal/aoc/day00/day00.go (about)

     1  package day00
     2  
     3  import (
     4  	"sort"
     5  	"strconv"
     6  	"strings"
     7  
     8  	"github.com/frodejac/aoc-2022/pkg/arraytools"
     9  )
    10  
    11  type Day00 struct {
    12  	elves []elf
    13  }
    14  
    15  func Solver(input []byte) *Day00 {
    16  	return &Day00{elves: parseInput(string(input))}
    17  }
    18  
    19  type elf struct {
    20  	inventory []int
    21  }
    22  
    23  func parseInput(input string) []elf {
    24  	input = strings.TrimSpace(input)
    25  	inputs := strings.Split(input, "\n\n")
    26  	elves := make([]elf, len(inputs))
    27  	for i, input := range inputs {
    28  		lines := strings.Split(input, "\n")
    29  		for _, line := range lines {
    30  			calories, err := strconv.Atoi(line)
    31  			if err != nil {
    32  				panic(err)
    33  			} else {
    34  				elves[i].inventory = append(elves[i].inventory, calories)
    35  			}
    36  		}
    37  	}
    38  	return elves
    39  }
    40  
    41  func (d *Day00) SolvePart1() string {
    42  	max := 0
    43  	for _, elf := range d.elves {
    44  		sum := arraytools.Sum(elf.inventory)
    45  		if sum > max {
    46  			max = sum
    47  		}
    48  	}
    49  	return strconv.Itoa(max)
    50  }
    51  
    52  func (d *Day00) SolvePart2() string {
    53  	invSizes := make([]int, len(d.elves))
    54  	for i, elf := range d.elves {
    55  		invSizes[i] = arraytools.Sum(elf.inventory)
    56  	}
    57  	sort.Slice(invSizes[:], func(i, j int) bool {
    58  		return invSizes[i] > invSizes[j]
    59  	})
    60  
    61  	total := arraytools.Sum(invSizes[:3])
    62  
    63  	return strconv.Itoa(total)
    64  }