This commit is contained in:
wagslane
2023-05-01 15:25:27 -06:00
parent f8912668b8
commit 9be3074de6
868 changed files with 58698 additions and 2 deletions

View File

@@ -0,0 +1,57 @@
package main
import (
"fmt"
"time"
)
func pingPong(numPings int) {
pings := make(chan struct{})
pongs := make(chan struct{})
go ponger(pings, pongs)
go pinger(pings, pongs, numPings)
}
// TEST SUITE - Don't touch below this line
func pinger(pings, pongs chan struct{}, numPings int) {
go func() {
sleepTime := 50 * time.Millisecond
for i := 0; i < numPings; i++ {
fmt.Println("ping", i, "sent")
pings <- struct{}{}
time.Sleep(sleepTime)
sleepTime *= 2
}
close(pings)
}()
i := 0
for range pongs {
fmt.Println("pong", i, "got")
i++
}
fmt.Println("pongs done")
}
func ponger(pings, pongs chan struct{}) {
i := 0
for range pings {
fmt.Println("ping", i, "got", "pong", i, "sent")
pongs <- struct{}{}
i++
}
fmt.Println("pings done")
close(pongs)
}
func test(numPings int) {
fmt.Println("Starting game...")
pingPong(numPings)
fmt.Println("===== Game over =====")
}
func main() {
test(4)
test(3)
test(2)
}

View File

@@ -0,0 +1,57 @@
package main
import (
"fmt"
"time"
)
func pingPong(numPings int) {
pings := make(chan struct{})
pongs := make(chan struct{})
go ponger(pings, pongs)
pinger(pings, pongs, numPings)
}
// TEST SUITE - Don't touch below this line
func pinger(pings, pongs chan struct{}, numPings int) {
go func() {
sleepTime := 50 * time.Millisecond
for i := 0; i < numPings; i++ {
fmt.Println("ping", i, "sent")
pings <- struct{}{}
time.Sleep(sleepTime)
sleepTime *= 2
}
close(pings)
}()
i := 0
for range pongs {
fmt.Println("pong", i, "got")
i++
}
fmt.Println("pongs done")
}
func ponger(pings, pongs chan struct{}) {
i := 0
for range pings {
fmt.Println("ping", i, "got", "pong", i, "sent")
pongs <- struct{}{}
i++
}
fmt.Println("pings done")
close(pongs)
}
func test(numPings int) {
fmt.Println("Starting game...")
pingPong(numPings)
fmt.Println("===== Game over =====")
}
func main() {
test(4)
test(3)
test(2)
}

View File

@@ -0,0 +1,39 @@
Starting game...
ping 0 sent
ping 0 got pong 0 sent
pong 0 got
ping 1 sent
ping 1 got pong 1 sent
pong 1 got
ping 2 sent
ping 2 got pong 2 sent
pong 2 got
ping 3 sent
ping 3 got pong 3 sent
pong 3 got
pings done
pongs done
===== Game over =====
Starting game...
ping 0 sent
ping 0 got pong 0 sent
pong 0 got
ping 1 sent
ping 1 got pong 1 sent
pong 1 got
ping 2 sent
ping 2 got pong 2 sent
pong 2 got
pings done
pongs done
===== Game over =====
Starting game...
ping 0 sent
ping 0 got pong 0 sent
pong 0 got
ping 1 sent
ping 1 got pong 1 sent
pong 1 got
pings done
pongs done
===== Game over =====

View File

@@ -0,0 +1,7 @@
# Ping Pong
Many tech companies play ping pong in the office during break time. At Mailio, we play virtual ping pong using channels.
## Assignment
Fix the bug in the `pingPong` function. It shouldn't `return` until the entire game of ping pong is complete.