File tree 3 files changed +85
-0
lines changed
3 files changed +85
-0
lines changed Original file line number Diff line number Diff line change 5
5
echo -e " \e[1m\e[38;5;0m\e[48;5;208m Consider using asdf-direnv! \e[0m"
6
6
fi
7
7
8
+ export GOMAXPROCS=1
9
+
8
10
source_env_if_exists .envrc.local
Original file line number Diff line number Diff line change
1
+ package fib
2
+
3
+ func FibRecursive (n int ) int {
4
+ if n <= 1 {
5
+ return n
6
+ }
7
+
8
+ return FibRecursive (n - 1 ) + FibRecursive (n - 2 )
9
+ }
10
+
11
+ var cache = map [int ]int {0 : 0 , 1 : 1 }
12
+
13
+ func FibCache (n int ) int {
14
+ if f , ok := cache [n ]; ok {
15
+ return f
16
+ }
17
+
18
+ cache [n ] = FibCache (n - 1 ) + FibCache (n - 2 )
19
+
20
+ return cache [n ]
21
+ }
Original file line number Diff line number Diff line change
1
+ package fib
2
+
3
+ import (
4
+ "strconv"
5
+ "testing"
6
+ )
7
+
8
+ func TestFibRecursive (t * testing.T ) {
9
+ tests := map [int ]int {
10
+ 0 : 0 ,
11
+ 1 : 1 ,
12
+ 2 : 1 ,
13
+ 3 : 2 ,
14
+ 4 : 3 ,
15
+ 5 : 5 ,
16
+ }
17
+ for i , v := range tests {
18
+ if f := FibRecursive (i ); f != v {
19
+ t .Fatalf ("FibRecursive(%v) == %v : expected %v" , i , f , v )
20
+ }
21
+ }
22
+ }
23
+
24
+ func TestFibCache (t * testing.T ) {
25
+ tests := map [int ]int {
26
+ 0 : 0 ,
27
+ 1 : 1 ,
28
+ 2 : 1 ,
29
+ 3 : 2 ,
30
+ 4 : 3 ,
31
+ 5 : 5 ,
32
+ }
33
+ for i , v := range tests {
34
+ if f := FibCache (i ); f != v {
35
+ t .Fatalf ("FibCache(%v) == %v : expected %v" , i , f , v )
36
+ }
37
+ }
38
+ }
39
+
40
+ func BenchmarkFibRecursive (b * testing.B ) {
41
+ ts := []int {1 , 10 , 40 }
42
+ for _ , t := range ts {
43
+ tc := func (b * testing.B ) {
44
+ for n := 0 ; n < b .N ; n ++ {
45
+ FibRecursive (t )
46
+ }
47
+ }
48
+ b .Run (strconv .Itoa (t ), tc )
49
+ }
50
+ }
51
+
52
+ func BenchmarkFibCache (b * testing.B ) {
53
+ ts := []int {1 , 10 , 40 }
54
+ for _ , t := range ts {
55
+ tc := func (b * testing.B ) {
56
+ for n := 0 ; n < b .N ; n ++ {
57
+ FibCache (t )
58
+ }
59
+ }
60
+ b .Run (strconv .Itoa (t ), tc )
61
+ }
62
+ }
You can’t perform that action at this time.
0 commit comments