Advertisement
Guest User

Untitled

a guest
Jan 2nd, 2015
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.29 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "time"
  6. )
  7.  
  8. func main() {
  9.    
  10.     //create channels
  11.     intchan := make(chan int)
  12.     floatchan1 := make(chan float64)
  13.     floatchan2 := make(chan float64)
  14.  
  15.     //launch go rountines
  16.     go fib(intchan)
  17.     go ratio(floatchan1, floatchan2)
  18.  
  19.     //initialize the process; pretty much fib(50)
  20.     intchan <- 50
  21.  
  22.     //print each number from fib() and ratio()
  23.     for i := 0; i < 50; i++ {
  24.         fibnum := <-intchan
  25.         floatchan1 <- float64(fibnum)
  26.  
  27.         //floatchan2 doesn't have any values in it; waiting
  28.         //for at least two values from floatchan1 in ratio()!
  29.         ratio := <-floatchan2
  30.         fmt.Println(fibnum, " - ", ratio)
  31.         time.Sleep(time.Millisecond * 250)
  32.     }
  33. }
  34.  
  35. //Pretty standard fib() function
  36. func fib(intchan chan int) {
  37.     var next, current, last int
  38.  
  39.     length := <-intchan
  40.  
  41.     for i := 0; i < length; i++ {
  42.         if current == 0 {
  43.             next = 1
  44.         } else {
  45.             next = current + last
  46.         }
  47.  
  48.         last = current
  49.         current = next
  50.  
  51.         //put fib() result to channel
  52.         intchan <- next
  53.     }
  54. }
  55.  
  56. func ratio(floatchan1 chan float64, floatchan2 chan float64) {
  57.     var ratio float64
  58.  
  59.     //get two consecutive values
  60.     x := <-floatchan1
  61.     y := <-floatchan1
  62.  
  63.     //ratio approches golden ratio as loop goes on
  64.     ratio = x / y
  65.  
  66.     //put ratio() result to channel to be printed in main()
  67.     floatchan2 <- ratio
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement