mchirico / zDaily

Playground to hack and test ideas with Zoe
1 stars 2 forks source link

Day 18: Type Switches and Trees #20

Open mchirico opened 3 years ago

mchirico commented 3 years ago

Video

Ref

package main

import "fmt"

type Zoe struct {}
type Susan struct {}

func do(i interface{}) {
    switch v := i.(type) {
    case int:
        fmt.Printf("Twice %v is %v\n", v, v*2)
    case string:
        fmt.Printf("%q is %v bytes long\n", v, len(v))
    case Zoe:
        fmt.Printf("I'm a Zoe\n")
    case Susan:
        fmt.Printf("I'm a Susan\n")
    default:
        fmt.Printf("I don't know about type %T!\n", v)
    }
}

func main() {
    do(21)
    do("hello")
    do(true)
    do(Zoe{})
    do(Susan{})
}

Tree

Ref

package main

import (
    "fmt"
    "math/rand"
)

// A Tree is a binary tree with integer values.
type Tree struct {
    Left  *Tree
    Value int
    Right *Tree
}

// New returns a new, random binary tree holding the values k, 2k, ..., 10k.
func New(k int) *Tree {
    var t *Tree
    for _, v := range rand.Perm(3) {
        t = insert(t, (1+v)*k)
    }
    return t
}

func insert(t *Tree, v int) *Tree {
    if t == nil {
        return &Tree{nil, v, nil}
    }
    if v < t.Value {
        t.Left = insert(t.Left, v)
    } else {
        t.Right = insert(t.Right, v)
    }
    return t
}

func (t *Tree) String() string {
    if t == nil {
        return "()"
    }
    s := ""
    if t.Left != nil {
        s += t.Left.String() + " "
    }
    s += fmt.Sprint(t.Value)
    if t.Right != nil {
        s += " " + t.Right.String()
    }
    return "(" + s + ")"
}

func main() {

    tree := New(200)
    fmt.Println(tree.String())
}
tacomonkautobot[bot] commented 3 years ago

mchirico, Thanks for opening this issue!

ZoeChiri commented 3 years ago

I hate trees >:(