Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "time"
  6. )
  7.  
  8. type Command struct {
  9. message string
  10. senderId int
  11. }
  12.  
  13. func main() {
  14. prev := make(chan Command)
  15. last := prev
  16. n := 1000
  17.  
  18. for i := 0; i < n - 1; i++ {
  19. next := make(chan Command)
  20. go process(i, prev, next)
  21. prev = next
  22. }
  23. go process(n - 1, prev, last)
  24. last <- Command{message:"Start", senderId: -1}
  25. time.Sleep(time.Second)
  26. }
  27.  
  28. /*func hardcodedJosephusRingFor4People() {
  29. chan1 := make(chan Command)
  30. chan2 := make(chan Command)
  31. chan3 := make(chan Command)
  32. chan4 := make(chan Command)
  33.  
  34. go process(0, chan4, chan1)
  35. go process(1, chan1, chan2)
  36. go process(2, chan2, chan3)
  37. go process(2, chan3, chan4)
  38.  
  39. chan4 <- Command{message:"Start", senderId: -1}
  40. time.Sleep(time.Second)
  41. }*/
  42.  
  43. func process(id int, left, right chan Command) {
  44. alive := true
  45. for {
  46. command := <-left
  47. //fmt.Printf("%+v\n", command)
  48. if command.message == "Start" {
  49. right <- Command{message:"kill", senderId:id}
  50. } else if command.message == "kill" && alive {
  51. //fmt.Printf("killing %d and passing sword\n", id)
  52. alive = false
  53. right <- Command{message:"passSword", senderId: command.senderId}
  54. } else if command.message == "kill" && !alive && command.senderId == id {
  55. continue
  56. } else if command.message == "kill" && !alive {
  57. right <- Command{message:"kill", senderId: command.senderId}
  58. } else if command.message == "passSword" && alive && command.senderId == id {
  59. fmt.Println("Survivor is", id)
  60. } else if command.message == "passSword" && alive {
  61. //fmt.Printf("%d has sword. kill next\n", id)
  62. right <- Command{message:"kill", senderId:id}
  63. } else if command.message == "passSword" && !alive {
  64. right <- Command{message:"passSword", senderId:command.senderId}
  65. }
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement