Day 6: Trash Compactor
Megathread guidelines
- Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
- You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL
FAQ
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465


Go
Part 2: Read the whole input in a rune matrix. Scan it column by column, store the numbers as you go, ignoring all spaces, and store the operand when you find it. When you hit an empty column or the end, do the operation and add it to the total.
spoiler
func part2() { // file, _ := os.Open("sample.txt") file, _ := os.Open("input.txt") defer file.Close() scanner := bufio.NewScanner(file) chars := [][]rune{} for scanner.Scan() { chars = append(chars, []rune(scanner.Text())) } m := len(chars) n := len(chars[0]) var op rune nums := []int{} total := 0 for j := range n { current := []rune{} for i := range m { if chars[i][j] == '+' || chars[i][j] == '*' { op = chars[i][j] } else if chars[i][j] != ' ' { current = append(current, chars[i][j]) } } if len(current) > 0 { x, _ := strconv.Atoi(string(current)) nums = append(nums, x) } if len(current) == 0 || j == n-1 { result := 0 if op == '*' { result = 1 } for _, x := range nums { if op == '+' { result = result + x } else { result = result * x } } total += result nums = []int{} } } fmt.Println(total) }