Last active
September 29, 2020 15:00
-
-
Save sarthakpranesh/ada67fd37908dc00567d5a08366d513a to your computer and use it in GitHub Desktop.
#100DayOfCode - Day 43/100 - FiboNacci number algo stress test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
) | |
func main() { | |
var fChan chan int = make(chan int) | |
var feChan chan int = make(chan int) | |
for i := 0; i < 100; i++ { | |
var n int = rand.Intn(50) | |
fmt.Printf("Val of n: %v\t", n) | |
go func() { | |
f := fiboNacci(n) | |
fmt.Printf("F: %v\t", f) | |
fChan <- f | |
}() | |
go func() { | |
fe := fiboNacciEfficient(n) | |
fmt.Printf("FE: %v\t", fe) | |
feChan <- fe | |
}() | |
if <-fChan != <-feChan { | |
fmt.Printf("Result: FALSE\n") | |
break | |
} | |
fmt.Printf("Result: TRUE\n") | |
} | |
} | |
// Slow and redundant recursive method, direct implementation of actual definition | |
func fiboNacci(n int) int { | |
if n <= 1 { | |
return n | |
} | |
return fiboNacci(n-1) + fiboNacci(n-2) | |
} | |
// Better solution with use of array, redundancy removed but not the best solution | |
func fiboNacciEfficient(n int) int { | |
if n <= 1 { | |
return n | |
} | |
var F []int = make([]int, n) | |
// assuming F1 = 1 and F2 = 1 | |
F[0] = 1 | |
F[1] = 1 | |
for i := 2; i < n; i++ { | |
F[i] = F[i-1] + F[i-2] | |
} | |
return F[n-1] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment