package main import ( "fmt" "strings" h "git.bullercodeworks.com/brian/adventofcode/helpers" ) func main() { inp := h.StdinToStringSlice() part1(inp) fmt.Println() part2(inp) } func part1(inp []string) { var ret int nums := pt1ParseNums(inp[:len(inp)-1]) var results []int ops := strings.Fields(inp[len(inp)-1]) results = pt1ApplyOps(ops, nums) for i := range results { ret = ret + results[i] } fmt.Println("# Part 1") fmt.Println(ret) } func part2(inp []string) { var ret int nums := pt2ParseNums(inp[:len(inp)-1]) var results []int ops := strings.Fields(inp[len(inp)-1]) results = pt2ApplyOps(ops, nums) for i := range results { ret = ret + results[i] } fmt.Println("# Part 2") fmt.Println(ret) } func pt1ParseNums(inp []string) [][]int { var nums [][]int for i := range inp { l := strings.Fields(inp[i]) // Row of numbers var n []int for j := range l { n = append(n, h.Atoi(l[j])) } nums = append(nums, n) } return nums } func pt2ParseNums(inp []string) [][]int { var nums [][]int var cols [][]byte for _, row := range inp { for j := range row { if len(cols) <= j { cols = append(cols, []byte{}) } cols[j] = append(cols[j], row[j]) } } var nCol []int for i := range cols { stC := string(cols[i]) if strings.TrimSpace(stC) == "" { if len(nCol) > 0 { nums = append(nums, nCol) nCol = []int{} } continue } nCol = append(nCol, h.Atoi(stC)) } if len(nCol) > 0 { nums = append(nums, nCol) } return nums } func pt1ApplyOps(ops []string, nums [][]int) []int { var res []int for i := range ops { var colRes int switch ops[i][0] { case '+': for j := range nums { colRes += nums[j][i] } case '*': colRes = 1 for j := range nums { colRes *= nums[j][i] } } res = append(res, colRes) } return res } func pt2ApplyOps(ops []string, nums [][]int) []int { var res []int for i := range nums { var colRes int switch ops[i][0] { case '+': for j := range nums[i] { colRes += nums[i][j] } case '*': colRes = 1 for j := range nums[i] { colRes *= nums[i][j] } } res = append(res, colRes) } return res }