Friday, April 27, 2018

Computing Fibonacci in Go

Had a coding whiteboard one of my first interviews back in early April.

It's nice to use Go Playground to prove it out and validate it after you get home.

For the whiteboard I had to do it iteratively. I added the recursive func after the fact

Here's the Go Playground link: https://play.golang.org/p/KDQaQlq8ONl

package main

import (
"fmt"
)

func main() {
fmt.Println("Hello, playground. Test for computing Fibonacci numbers")

computeFibonacci(10)
computeFibonacciRecursively(10, 0, 1)
}

func computeFibonacci(numberOfNumbers int) {

penultimate := 0
ultimate := 1

fmt.Printf("\nNext number (iterative): %d", penultimate)
fmt.Printf("\nNext number (iterative): %d", ultimate)

for i := 2; i < numberOfNumbers; i++ {

currentSum := penultimate + ultimate
fmt.Printf("\nNext number (iterative): %d", currentSum)
penultimate = ultimate
ultimate = currentSum

}

}

func computeFibonacciRecursively(numberOfNumbers int, penultimate int, ultimate int) {

if numberOfNumbers == 0 {
return
} else {
fmt.Printf("\nNext number (recurse method): %d", penultimate)
numberOfNumbers--
computeFibonacciRecursively(numberOfNumbers, ultimate, penultimate+ultimate)

}

}

No comments:

Exploring ELK (Elastic) Stack for hack-a-thon

At my current gig, our group finally got to do hack-a-thon week and I joined a team project that tied together a few of the technologies I&#...