Skip to content

Instantly share code, notes, and snippets.

@chinmay185
Created March 25, 2017 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chinmay185/2631f6938bb3e8fa903b8379e25ed6e3 to your computer and use it in GitHub Desktop.
Save chinmay185/2631f6938bb3e8fa903b8379e25ed6e3 to your computer and use it in GitHub Desktop.
Simulates Josephus problem solution using Goroutines and Channels
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}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment