Advent of Code 2021 Day 1: Sonar Sweep
By Andreas Røssland
https://adventofcode.com/2021/day/1 https://github.com/roessland/advent-of-code
Simple stuff, and a small trick.
- My first thought was that I could just loop over the sliding window and that this is more than good enough.
- But what if the window was much bigger? One could compute a prefix sum array when reading input,
ps[i] = n[0] + ... + n[i]
so that you can doS0 := ps[i-1]-ps[i-4]
instead ofS0 := nums[i-1] + nums[i-2] + nums[i-3]
. This doesn’t make much sense in this case since the sliding window is so small, but could be useful for much larger windows, or if the window size varies along the data. - Possible improvement: Don’t read entire input before starting processing. Instead compute as the data is read by maintaining
ps[i-1]
andps[i-4]
as you loop through the data. Similar to a circular buffer. - At this point I realize that the inequality
nums[i] + nums[i-1] + nums[i-2] > nums[i-1] + nums[i-2] + nums[i-3]
can be simplified tonums[i] > nums[i-3]
and all the previous points are moot.
package main
import (
"bufio"
"fmt" "log" "os" "strconv")
func part1(nums []int) {
incs := 0
for i := 1; i < len(nums); i++ {
if nums[i] > nums[i-1] {
incs++
}
}
fmt.Println("Part 1: ", incs)
}
func part2(nums []int) {
incs := 0
for i := 3; i < len(nums); i++ {
if nums[i] > nums[i-3] {
incs++
}
}
fmt.Println("Part 2: ", incs)
}
func main() {
f, err := os.Open("input.txt")
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(f)
var nums []int
for scanner.Scan() {
line := scanner.Text()
n, err := strconv.Atoi(line)
if err != nil {
panic("nope")
}
nums = append(nums, n)
}
part1(nums)
part2(nums)
}