For anyone who doesn’t know, advent of code is a series of coding challenges that happens every year. It’s made to be like an advent calendar, with one programming challenge released per day until Christmas. Something interesting about this is that since the challenges only need the output of the program, you can do it in any language you want. I thought it might be interesting to compare and discuss solutions (ideally spoilered in case anyone hasn’t completed the challenge yet).

Thoughts?

  • loathsome dongeaterA
    link
    fedilink
    English
    arrow-up
    1
    ·
    11 months ago

    My solution for day 1:

    golang
    import (
    	"bufio"
    	"fmt"
    	"os"
    	"strings"
    )
    
    func check(e error) {
    	if e != nil {
    		panic(e)
    	}
    }
    
    // Part 1
    func parseLinePartOne(line string) int {
    	var first, last int
    	foundFirst := false
    	for i := 0; i < len(line); i++ {
    		if line[i] >= '0' && line[i] <= '9' {
    			if !foundFirst {
    				first = int(line[i] - '0')
    				foundFirst = true
    			}
    			last = int(line[i] - '0')
    		}
    	}
    	return first*10 + last
    }
    
    // Part 2
    func stringToDigit(str string) (int, bool) {
    	digits := map[string]int{
    		"one":   1,
    		"two":   2,
    		"three": 3,
    		"four":  4,
    		"five":  5,
    		"six":   6,
    		"seven": 7,
    		"eight": 8,
    		"nine":  9,
    	}
    	if str[0] >= '0' && str[0] <= '9' {
    		return int(str[0] - '0'), true
    	}
    	for k, v := range digits {
    		if strings.HasPrefix(str, k) {
    			return v, true
    		}
    	}
    	return 0, false
    }
    
    func parseLinePartTwo(line string) int {
    	first, last := 0, 0
    	for i := 0; i < len(line); i++ {
    		n, ok := stringToDigit(line[i:])
    		if ok {
    			first = n
    			break
    		}
    	}
    	for i := len(line) - 1; i >= 0; i-- {
    		n, ok := stringToDigit(line[i:])
    		if ok {
    			last = n
    			break
    		}
    	}
    	return first*10 + last
    }
    
    func main() {
    	file, err := os.Open("./input.txt")
    	check(err)
    	defer file.Close()
    
    	scanner := bufio.NewScanner(file)
    	partOne, partTwo := 0, 0
    	for scanner.Scan() {
    		line := scanner.Text()
    		partOne += parseLinePartOne(line)
    		partTwo += parseLinePartTwo(line)
    	}
    	check(scanner.Err())
    	fmt.Println("Part 1:", partOne)
    	fmt.Println("Part 2:", partTwo)
    }