Last active
May 12, 2025 09:20
-
-
Save ShawonAshraf/d8eacf41346e5f17e35c3780a26bd53c to your computer and use it in GitHub Desktop.
Tour of Go exercises
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" | |
// fibonacci is a function that returns | |
// a function that returns an int. | |
func fibonacci() func() int { | |
n := 0 // position of the number | |
prev := 0 | |
next := 1 | |
// fibonacci number | |
fib := 0 | |
return func() int { | |
switch n { | |
case 0: | |
n += 1 | |
return 0 | |
case 1: | |
n += 1 | |
return 1 | |
default: | |
n += 1 | |
fib = next + prev | |
prev = next | |
next = fib | |
return fib | |
} | |
} | |
} | |
func main() { | |
f := fibonacci() | |
for i := 0; i < 10; i++ { | |
fmt.Println(f()) | |
} | |
} |
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 ( | |
"strings" | |
"golang.org/x/tour/wc" | |
) | |
func WordCount(s string) map[string]int { | |
words := strings.Fields(s) | |
countMap := map[string]int{} | |
for w := range words { | |
current := words[w] | |
// if it exists | |
if _, ok := countMap[current]; ok { | |
countMap[current] = countMap[current] + 1 | |
} else { | |
countMap[current] = 1 | |
} | |
} | |
return countMap | |
} | |
func main() { | |
wc.Test(WordCount) | |
} |
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 "golang.org/x/tour/pic" | |
func Pic(dx, dy int) [][]uint8 { | |
im := make([][]uint8, dy) | |
for y := range im { | |
im[y] = make([]uint8, dx) | |
for x := range im[y] { | |
im[y][x] = uint8(x^y) | |
} | |
} | |
return im | |
} | |
func main() { | |
pic.Show(Pic) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment