Last active
July 21, 2020 09:58
-
-
Save awadhwana/25a89558e3b1ccf8982cc2fb6cfa4414 to your computer and use it in GitHub Desktop.
Solution for Exercises on A Tour of Go
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
//Exercise: Maps | |
//Implement WordCount. | |
//It should return a map of the counts of each “word” in the string s. | |
//The wc.Test function runs a test suite against the provided function and prints success or failure. | |
package main | |
import ( | |
"strings" | |
"golang.org/x/tour/wc" | |
) | |
func WordCount(s string) map[string]int { | |
stringSlice := make(map[string]int) | |
words := strings.Fields(s) | |
for _, v := range words { | |
stringSlice[v]++ | |
} | |
return stringSlice | |
} | |
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
//Exercise: Slices | |
//Implement Pic. It should return a slice of length dy, each element of which is a slice of dx 8-bit unsigned integers. | |
//When you run the program, it will display your picture, interpreting the integers as grayscale (well, bluescale) values. | |
//The choice of image is up to you. Interesting functions include (x+y)/2, x*y, and x^y. | |
package main | |
import ( | |
"golang.org/x/tour/pic" | |
) | |
func Pic(dx, dy int) [][]uint8 { | |
//using make to create a slice of length dy | |
pic := make([][]uint8, dy) | |
for i := 0; i < dy; i++ { | |
//using make to create a slice of length dx | |
pic[i] = make([]uint8, dx) | |
} | |
//creating image | |
for y, _ := range pic { | |
for x, _ := range pic[y] { | |
//choice for image | |
//pic[y][x] = uint8(x ^ y) | |
pic[y][x] = uint8(x+y)/2 | |
//pic[y][x] = uint8(x-y) | |
//pic[y][x] = uint8((x <<uint8(y))/2) | |
} | |
} | |
return pic | |
} | |
func main() { | |
pic.Show(Pic) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment