DEV Community

Discussion on: AoC Day 2: Inventory Management System

Collapse
 
thejessleigh profile image
jess unrein

My solutions for part 1

Python

def checksum(inputs):
    ids = inputs.read().splitlines()
    twos = 0
    threes = 0
    for row in ids:
        seen = {}
        for letter in row:
            seen[letter] = seen.get(letter, 0) + 1
        if 2 in seen.values():
            twos += 1
        if 3 in seen.values():
            threes += 1

    return twos * threes

checksum(open('input.txt', 'r'))

Go

package main

import (
    "strings"
    "io/ioutil"
)

func containsVal(m map[string]int, v int)(bool) {
    for _, x := range m{
        if x == v {
            return true
        }
    }
    return false
}

func checksum(x string)(int) {
    two := 0
    three := 0
    ids := strings.Split(x, "\n")
    for i := 0; i < len(ids); i++ {
        counter := make( map[string]int )
        s := strings.Split(ids[i], "")
        for _, l := range s {
            counter[l]++
        }
        if containsVal(counter, 2) {
            two++
        }
        if containsVal(counter, 3) {
            three++
        }
    }
    return two * three
}

func main() {
    f, err := ioutil.ReadFile("input.txt")
    if err != nil {
        panic(err)
    }
    checksum(string(f))
}

Benchmark difference

`python3 2_1.py` 100 times
real    0m4.744s
user    0m3.129s
sys 0m0.967s

`go run 2_1.go` 100 times
real    0m37.649s
user    0m28.807s
sys 0m14.105s

go build

`./2_1` 100 times
real    0m0.709s
user    0m0.327s
sys 0m0.280s