2021 Day 1

Posted on Dec 1, 2021

Part 1

Problem

Take a list of numbers from a file (one per line) and count the occasions where a number is greater than the one before it.

General solution

Read in each line and store in a variable length array (or similar structure, depending on the language). Iterate over the array and count all instances where a[index] > a[index - 1], excluding index == 0.

Alternatively, read in each line and keep a record of the previous line to compare with. This would involve less code and less memory, since building an array of lines means effectively loading the entire file into memory. This is probably not an optimisation worth making for a problem with limited input, but may be necessary if the file was particularly large (e.g. several hundred megabytes).

Solution: Go

Scan the input (os.Stdin) and add each line to a slice (Go’s equivalent to a variable length array in PHP). Iterate over the slice with for and print the final count.

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	increasedMeasurements := 0
	var input []int

	for scanner.Scan() {
		number, _ := strconv.Atoi(scanner.Text())
		input = append(input, number)
	}

	for i := range input {
		if i > 0 && input[i] > input[i-1] {
			increasedMeasurements++
		}
	}

	fmt.Println(increasedMeasurements)
}

Part 2

Problem

As in part 1, take a list of numbers, but this time compare the sums of three number moving windows.

Solution: Go

Read the file as in part 1, then calculate the sums of all the moving windows into an array. Finally, perform the same count as in part 1, but on the slice of moving windows.

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	increasedMeasurements := 0
	var input []int

	// Read file into slice, converting to integers
	for scanner.Scan() {
		number, _ := strconv.Atoi(scanner.Text())
		input = append(input, number)
	}

	// Calculate all the windows
	var windowSums []int
	windowSize := 3
	lastWindowIndex := len(input) - (windowSize - 1)

	for i := 0; i < lastWindowIndex; i++ {
		windowSums = append(windowSums, input[i]+input[i+1]+input[i+2])
	}

	// Count all the windows that are greater than the previous window
	for ws := range windowSums {
		if ws > 0 && windowSums[ws] > windowSums[ws-1] {
			increasedMeasurements++
		}
	}

	fmt.Println(increasedMeasurements)
}