Skip to content

Instantly share code, notes, and snippets.

@satoryu
Last active May 17, 2019 05:26
Show Gist options
  • Save satoryu/c64ac391740e0833992d3a1deb4b5055 to your computer and use it in GitHub Desktop.
Save satoryu/c64ac391740e0833992d3a1deb4b5055 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"golang.org/x/tour/tree"
)
// 1.
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
if t == nil {
close(ch)
return
}
c := make(chan int)
go Walk(t.Left, c)
for v := range c {
ch <- v
}
ch <- t.Value
c = make(chan int)
go Walk(t.Right, c)
for v := range c {
ch <- v
}
close(ch)
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch1, ch2 := make(chan int), make(chan int)
go Walk(t1, ch1)
go Walk(t2, ch2)
a1 := []int{}
for v := range ch1 {
a1 = append(a1, v)
}
a2 := []int{}
for v := range ch2 {
a2 = append(a2, v)
}
if len(a1) != len(a2) {
return false
}
for i, v := range a1 {
if v != a2[i] {
return false
}
}
return true
}
func main() {
// 2.
ch := make(chan int)
go Walk(tree.New(10), ch)
for v := range ch {
fmt.Println(v)
}
// 4.
fmt.Println(Same(tree.New(1), tree.New(1))) // => true
fmt.Println(Same(tree.New(10), tree.New(10))) // => true
fmt.Println(Same(tree.New(1), tree.New(10))) // => false
}
package main
import (
"fmt"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return "cannot Sqrt negative number: -2"
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return x, ErrNegativeSqrt(x)
}
return x, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
sequence := map[int]int{
0: 0,
1: 1,
}
n := 0
return func() int {
defer func() { n++ }()
if v, ok := sequence[n]; ok {
return v
}
sequence[n] = sequence[n-1] + sequence[n-2]
return sequence[n]
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
package main
import (
"image"
"image/color"
"golang.org/x/tour/pic"
)
type Image struct{
width, height int
}
func (img Image) Bounds() image.Rectangle {
return image.Rect(0, 0, img.width, img.height)
}
func (img Image) ColorModel() color.Model {
return color.RGBAModel
}
func (img Image) At(x, y int) color.Color {
return color.RGBA{uint8(2 * x), uint8(2 * y), uint8(x * y), 255}
}
func main() {
m := Image{255,255}
pic.ShowImage(m)
}
package main
import (
"strings"
"golang.org/x/tour/wc"
)
func WordCount(s string) map[string]int {
word_counts := map[string]int{}
words := strings.Fields(s)
for _, word := range words {
word_counts[word]++
}
return word_counts
}
func main() {
wc.Test(WordCount)
}
package main
import "golang.org/x/tour/reader"
type MyReader struct{}
// TODO: Add a Read([]byte) (int, error) method to MyReader.
func (myReader MyReader) Read(b []byte) (int, error) {
n := len(b)
for i := 0; i < n; i++ {
b[i] = 'A'
}
return n, nil
}
func main() {
reader.Validate(MyReader{})
}
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
func RotateBy13Places(c byte) byte {
if c >= 'A' && c <= 'Z' {
return (((c - 'A') + 13) % 26) + 'A'
} else if c >= 'a' && c <= 'z' {
return (((c - 'a') + 13) % 26) + 'a'
}
return c
}
func (rot *rot13Reader) Read(p []byte) (int, error) {
b := make([]byte, len(p))
n, err := rot.r.Read(b)
for i := 0; i < n; i++ {
p[i] = RotateBy13Places(b[i])
}
return n, err
}
func main() {
s := strings.NewReader("Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
package main
import (
"golang.org/x/tour/pic"
)
func Pic(dx, dy int) [][]uint8 {
pixels := make([][]uint8, 0, dy)
for y := 0; y < dy; y++ {
line := make([]uint8, 0, dx)
for x := 0; x < dx; x++ {
line = append(line, uint8(x^y + y^x))
}
pixels = append(pixels, line)
}
return pixels
}
func main() {
pic.Show(Pic)
}
package main
import (
"fmt"
"strings"
)
type IPAddr [4]byte
func (addr IPAddr) String() string {
str := make([]string, 0, 4)
for _, v := range addr {
str = append(str, string(v))
}
return strings.Join(str, ".")
}
func main() {
hosts := map[string]IPAddr{
"loopback": {127, 0, 0, 1},
"googleDNS": {8, 8, 8, 8},
}
for name, ip := range hosts {
fmt.Printf("%v: %v\n", name, ip)
}
}
package main
import (
"fmt"
"sync"
)
type Fetcher interface {
// Fetch returns the body of URL and
// a slice of URLs found on that page.
Fetch(url string) (body string, urls []string, err error)
}
type Cache struct {
body string
urls []string
}
var cachedResponses = map[string]Cache{}
var mux sync.Mutex
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {
// TODO: Fetch URLs in parallel.
// TODO: Don't fetch the same URL twice.
// This implementation doesn't do either:
if depth <= 0 {
return
}
var (
body string
urls []string
err error
)
mux.Lock()
cache, exists := cachedResponses[url]
mux.Unlock()
if exists {
body, urls, err = cache.body, cache.urls, nil
} else {
body, urls, err = fetcher.Fetch(url)
mux.Lock()
cachedResponses[url] = Cache{body, urls}
mux.Unlock()
}
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("found: %s %q\n", url, body)
var wg sync.WaitGroup
for _, url := range urls {
wg.Add(1)
go func(u string, d int, f Fetcher) {
defer wg.Done()
Crawl(u, d, f)
}(url, depth - 1, fetcher)
}
wg.Wait()
return
}
func main() {
Crawl("https://golang.org/", 4, fetcher)
}
// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher map[string]*fakeResult
type fakeResult struct {
body string
urls []string
}
func (f fakeFetcher) Fetch(url string) (string, []string, error) {
if res, ok := f[url]; ok {
return res.body, res.urls, nil
}
return "", nil, fmt.Errorf("not found: %s", url)
}
// fetcher is a populated fakeFetcher.
var fetcher = fakeFetcher{
"https://golang.org/": &fakeResult{
"The Go Programming Language",
[]string{
"https://golang.org/pkg/",
"https://golang.org/cmd/",
},
},
"https://golang.org/pkg/": &fakeResult{
"Packages",
[]string{
"https://golang.org/",
"https://golang.org/cmd/",
"https://golang.org/pkg/fmt/",
"https://golang.org/pkg/os/",
},
},
"https://golang.org/pkg/fmt/": &fakeResult{
"Package fmt",
[]string{
"https://golang.org/",
"https://golang.org/pkg/",
},
},
"https://golang.org/pkg/os/": &fakeResult{
"Package os",
[]string{
"https://golang.org/",
"https://golang.org/pkg/",
},
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment