DEV Community

Cover image for DAY 2 - Advent of Code 2020 w/ GoLang
Edvin
Edvin

Posted on • Edited on

1

DAY 2 - Advent of Code 2020 w/ GoLang

DAY 2:
You can’t access indices of a string like an array. They are immutable. You’ll need to convert it to a rune or byte array.

package days

import (
    "fmt"
    "strconv"
    "strings"

    inputs "../inputs"
)

// Two : advent of code, day two part1 and 2.
func Two() {
    inputSlice := inputs.Day2

    partOneSlice := []string{}
    partTwoSlice := []string{}

    for i := 0; i < len(inputSlice); i++ {
        rangeSlice := getRange(inputSlice[i])
        ruleAndPassSlice := getRuleAndPass(inputSlice[i])

        occurances := strings.Count(ruleAndPassSlice[1], ruleAndPassSlice[0])
        if occurances >= rangeSlice[0] && occurances <= rangeSlice[1] {
            partOneSlice = append(partOneSlice, inputSlice[i])
        }

        if checkIndices(ruleAndPassSlice[1], []rune(ruleAndPassSlice[0])[0], rangeSlice[0], rangeSlice[1]) {
            partTwoSlice = append(partTwoSlice, inputSlice[i])
        }

    }

    fmt.Print("Part 1: ")
    fmt.Println(len(partOneSlice))

    fmt.Print("Part 2: ")
    fmt.Println(len(partTwoSlice))
}

func checkIndices(in string, r rune, first int, last int) bool {
    toRune := []rune(in)
    return ((toRune[first-1] == r && toRune[last-1] != r) || (toRune[first-1] != r && toRune[last-1] == r))
}

func getRange(input string) []int {
    splitter := strings.Split(input, " ")
    rangeAsStrings := strings.Split(splitter[0], "-")

    rangeAsInts := make([]int, len(rangeAsStrings))

    for i, s := range rangeAsStrings {
        rangeAsInts[i], _ = strconv.Atoi(s)
    }

    return rangeAsInts
}

func getRuleAndPass(input string) []string {
    splitter := strings.Split(input, " ")
    ruleAndPass := []string{strings.Replace(splitter[1], ":", "", -1), splitter[2]}

    return ruleAndPass
}

Enter fullscreen mode Exit fullscreen mode

Link to Github source file

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay