You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
aoc2020/day07/parse.go

50 lines
958 B

package day07
import (
"regexp"
"strconv"
"strings"
"git.elis.nu/etu/aoc2020/utils"
)
type Bag struct {
Type string
Carries map[string]int
}
var rows []Bag
func ParseFile(input string) {
// Parse file
for _, line := range utils.GetLinesFromFile("day07/" + input + ".txt") {
re := regexp.MustCompile(`^([\s\w]+) bags contain no other bags.$`)
if match := re.FindStringSubmatch(line); len(match) > 0 {
rows = append(rows, Bag{
Type: match[1],
})
} else {
re = regexp.MustCompile(`^([\s\w]+) bags contain ([^\.]+).$`)
matches := re.FindStringSubmatch(line)
row := Bag{
Type: matches[1],
Carries: make(map[string]int),
}
for _, rule := range strings.Split(matches[2], ", ") {
re = regexp.MustCompile(`(\d+) ([\s\w]+) bags?`)
matches2 := re.FindStringSubmatch(rule)
amount, _ := strconv.Atoi(matches2[1])
row.Carries[matches2[2]] = amount
}
rows = append(rows, row)
}
}
}