Skip to content

Instantly share code, notes, and snippets.

@atomaths
Forked from todoa2c/santa.go
Created July 30, 2013 11:35
Show Gist options
  • Save atomaths/6112196 to your computer and use it in GitHub Desktop.
Save atomaths/6112196 to your computer and use it in GitHub Desktop.
// サンタクロース問題
// http://karetta.jp/article/blog/oneline/030756
package main
import (
"fmt"
"math/rand"
"reflect"
"time"
)
var r *rand.Rand
type visitor interface {
act(home chan visitor)
}
type elf struct {
id int
}
type reindeer struct {
id int
}
func (d elf) act(home chan visitor) {
time.Sleep(time.Duration(r.Int63n(10)) * time.Second)
fmt.Printf("Elf #%d came to Santa's home\n", d.id)
home <- d
}
func (c reindeer) act(home chan visitor) {
time.Sleep(time.Duration(r.Int63n(8)) * time.Second)
fmt.Printf("Reindeer #%d came to Santa's home\n", c.id)
home <- c
}
func startReindeers(home chan visitor) {
for i := 0; i < 9; i++ {
c := reindeer{i}
go c.act(home)
}
}
func startElfs(home chan visitor) {
for i := 0; i < 10; i++ {
d := elf{i}
go d.act(home)
}
}
func release(all []visitor, home chan visitor) []visitor {
for _, member := range all {
go member.act(home)
}
return queue()
}
func queue() []visitor {
return make([]visitor, 0, 10)
}
func main() {
r = rand.New(rand.NewSource(time.Now().Unix()))
home := make(chan visitor)
startReindeers(home)
startElfs(home)
reindeers := queue()
elfs := queue()
for i := 0; i < 50; i++ {
visitor := <-home
name := reflect.TypeOf(visitor).Name()
if name == "reindeer" {
reindeers = append(reindeers, visitor)
} else if name == "elf" {
elfs = append(elfs, visitor)
}
if len(reindeers) == 9 {
fmt.Println("*** Santa went to deliver presents: ", reindeers)
time.Sleep(time.Duration(10) * time.Second)
reindeers = release(reindeers, home)
fmt.Println("*** Delivery finished")
}
if len(elfs) == 3 {
fmt.Println("### Santa is meeting up with elfs: ", elfs)
time.Sleep(time.Duration(5) * time.Second)
elfs = release(elfs, home)
fmt.Println("### Meeting finished")
}
}
fmt.Println("Finished.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment