開発環境
- macOS Catalina - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Go (プログラミング言語)
入門Goプログラミング (Nathan Youngman(著)、Roger Peppé(著)、吉川 邦夫(監修, 翻訳)、翔泳社)のUNIT 7(並行プログラミング)、LESSON 30(ゴルーチンと並行性)の練習問題-1の解答を求めてみる。
コード
package main
import (
"fmt"
"math/rand"
"time"
)
func send(c chan string) {
strs := []string{"Go", "Rust"}
for i := 0; i < 20; i++ {
c <- strs[rand.Intn(len(strs))]
}
close(c)
}
func remove(c1, c2 chan string) {
pre := ""
for s := range c1 {
if pre != s {
c2 <- s
pre = s
}
}
close(c2)
}
var count int = 1
func print(c chan string) {
for v := range c {
fmt.Printf("%2v: %v\n", count, v)
count++
}
}
func main() {
rand.Seed(time.Now().UnixNano())
c0 := make(chan string)
c1 := make(chan string)
go send(c0)
go remove(c0, c1)
print(c1)
}
入出力結果(Zsh、PowerShell、Terminal)
% go run ./remove-identical.go
1: Rust
2: Go
3: Rust
4: Go
5: Rust
6: Go
7: Rust
8: Go
9: Rust
10: Go
% go run ./remove-identical.go
1: Go
2: Rust
3: Go
4: Rust
5: Go
6: Rust
7: Go
8: Rust
9: Go
% go run ./remove-identical.go
1: Go
2: Rust
3: Go
4: Rust
5: Go
6: Rust
7: Go
8: Rust
9: Go
10: Rust
% go run ./remove-identical.go
1: Go
2: Rust
3: Go
4: Rust
5: Go
6: Rust
% go run ./remove-identical.go
1: Go
2: Rust
3: Go
4: Rust
5: Go
6: Rust
7: Go
8: Rust
9: Go
10: Rust
11: Go
12: Rust
%
0 コメント:
コメントを投稿