advent-of-code/2023/day-5/almanac.go
2023-12-05 19:57:53 +00:00

102 lines
2.4 KiB
Go

package main
import (
"fmt"
"strconv"
"strings"
"unicode"
)
const (
seedToSoilMap = "seed-to-soil map"
soilToFertilizerMap = "soil-to-fertilizer map"
fertilizerToWaterMap = "fertilizer-to-water map"
waterToLightMap = "water-to-light map"
lightToTemperatureMap = "light-to-temperature map"
temperatureToHumidityMap = "temperature-to-humidity map"
humidityToLocationMap = "humidity-to-location map"
)
type almanac struct {
seeds []int
seedToSoil map[int]int
soilToFertilizer map[int]int
fertilizerToWater map[int]int
waterToLight map[int]int
lightToTemperature map[int]int
temperatureToHumidity map[int]int
humidityToLocation map[int]int
}
func parseAlmanac(contents []string) (almanac, error) {
// Assumption: The first line always contains the seed numbers. An error is returned
// if this is not the case or if the format is all wrong.
seeds, err := parseSeedNums(contents[0])
if err != nil {
return almanac{}, fmt.Errorf("unable to parse the seed numbers; %w", err)
}
// mapLines = []string{}
// loop while contents > 0
// if line is blank
// if map lines > 0 -> parse map and populate relevant field
// mapLines = []string{}
// else
// if first rune is digit, add line to mapLines:
// else get map name
output := almanac{
seeds: seeds,
}
return output, nil
}
func parseSeedNums(seedStr string) ([]int, error) {
expectedPrefix := "seeds:"
if !strings.HasPrefix(seedStr, expectedPrefix) {
return nil, fmt.Errorf("%q does not begin with %s", seedStr, expectedPrefix)
}
seedStr = seedStr[strings.Index(seedStr, ":")+1:]
seeds := []int{}
seedNum := ""
addSeed := func(digit string) error {
value, err := strconv.Atoi(digit)
if err != nil {
return fmt.Errorf("unable to convert %q to int; %w", digit, err)
}
seeds = append(seeds, value)
return nil
}
for ind, s := range seedStr {
if unicode.IsDigit(s) {
seedNum = seedNum + string(s)
if ind == len(seedStr)-1 {
if err := addSeed(seedNum); err != nil {
return nil, fmt.Errorf("unable to add %q to seeds; %w", seedNum, err)
}
}
} else {
if len(seedNum) > 0 {
if err := addSeed(seedNum); err != nil {
return nil, fmt.Errorf("unable to add %q to seeds; %w", seedNum, err)
}
}
seedNum = ""
}
}
return seeds, nil
}
func parseMap(mapLines []string) (map[int]int, error) {
var mapMatrix [][]int
return nil, nil
}