Skip to content

Instantly share code, notes, and snippets.

@derekkenney
Last active January 28, 2019 14:33
Show Gist options
  • Save derekkenney/88f845f84314f3aed8d9aa4bacdc8404 to your computer and use it in GitHub Desktop.
Save derekkenney/88f845f84314f3aed8d9aa4bacdc8404 to your computer and use it in GitHub Desktop.
Finding the linear run-time of a Go function
package main
import "fmt"
//Create an array with a length of 10k
var galaxy [10000]string
var bigO int
//Worst case scenario. Have to go through 10k records
func findDagobah() {
fmt.Println("Where is Yoda?")
for i := 0; i < len(galaxy); i++ {
if galaxy[i] == "Dagobah" {
fmt.Println("Dagobah")
fmt.Printf("Searched %d systems for Yoda\n", bigO)
}
bigO++
}
}
//More scalable solution. Breaks when match is found
func findRebels() {
fmt.Printf("\nWhere are the rebel's hiding?\n")
bigO = 0
for i := 0; i < len(galaxy); i++ {
if galaxy[i] == "Yavin4" {
fmt.Println("Yavin4")
fmt.Printf("Searched %d systems for the Rebels", bigO)
break
}
bigO++
}
}
func main() {
//Set planets to array index
galaxy[404] = "Dagobah"
galaxy[2000] = "Yavin4"
findDagobah()
findRebels()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment