Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "time"
- )
- type Command struct {
- message string
- senderId int
- }
- func main() {
- prev := make(chan Command)
- last := prev
- n := 1000
- for i := 0; i < n - 1; i++ {
- next := make(chan Command)
- go process(i, prev, next)
- prev = next
- }
- go process(n - 1, prev, last)
- last <- Command{message:"Start", senderId: -1}
- time.Sleep(time.Second)
- }
- /*func hardcodedJosephusRingFor4People() {
- chan1 := make(chan Command)
- chan2 := make(chan Command)
- chan3 := make(chan Command)
- chan4 := make(chan Command)
- go process(0, chan4, chan1)
- go process(1, chan1, chan2)
- go process(2, chan2, chan3)
- go process(2, chan3, chan4)
- chan4 <- Command{message:"Start", senderId: -1}
- time.Sleep(time.Second)
- }*/
- func process(id int, left, right chan Command) {
- alive := true
- for {
- command := <-left
- //fmt.Printf("%+v\n", command)
- if command.message == "Start" {
- right <- Command{message:"kill", senderId:id}
- } else if command.message == "kill" && alive {
- //fmt.Printf("killing %d and passing sword\n", id)
- alive = false
- right <- Command{message:"passSword", senderId: command.senderId}
- } else if command.message == "kill" && !alive && command.senderId == id {
- continue
- } else if command.message == "kill" && !alive {
- right <- Command{message:"kill", senderId: command.senderId}
- } else if command.message == "passSword" && alive && command.senderId == id {
- fmt.Println("Survivor is", id)
- } else if command.message == "passSword" && alive {
- //fmt.Printf("%d has sword. kill next\n", id)
- right <- Command{message:"kill", senderId:id}
- } else if command.message == "passSword" && !alive {
- right <- Command{message:"passSword", senderId:command.senderId}
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement