devpapa

Writing more Go

I've been thinking of a way to practice writing more Go. I've exhausted the free lessons on Codecademy but I want to write more in the language. In a previous post, I wrote an unoptimized Bubblesort in Go, and I could do more Data Structures and Algorithm in Go but I wanted something different.

I've started the advent of code problems from 2015 when the first problems were posted and I've solved the first question.

This problem is quite simple:

In the first part, you are asked to find out the floor our Santa is on by reading a series of parentheses. An opening parenthesis, (, means he goes up by one floor, and a closing parenthesis, ), means he goes down by one floor. Given a series of parentheses, figure out what floor our Santa is on.

The second part asks you to find out the first instance where our Santa enters the basement of the building.

The floorPicker function returns two values, the first value is the floor Santa is on, the second is the value of the position of the first instance where he enters the basement; a -1 value.

package main

import (
    "fmt"
)

func floorPicker(strInput string) (int, int) {
    floor := 0
    var firstBasementValues []int
    for idx, val := range strInput {
    	if string(val) == ")" {
    		floor -= 1
    	} else if string(val) == "(" {
    		floor += 1
    	} else {
    		continue
    	}
    	if floor == -1 {
    		// we offset by 1 because they ask for position not index
    		firstBasementValues = append(firstBasementValues, idx+1)
    	}
    }
    return floor, firstBasementValues[0]
}

func main() {
    fmt.Println("Hello World")
    flr, baseval := floorPicker(`()(((()))(()()))))))`)
    fmt.Println("you are on floor:", flr, " first basement value is:", baseval)
}

I'm in love with this syntax, I think it's elegant. Say whatever you want about Ruby but this is just beautiful to my eye.

I haven't yet decided if I will post every exercise but I sure will share what I'm learning on this journey.

Are you writing Go? What should I be spending more time on?

#go