-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
122 lines (106 loc) · 2 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
"sync"
"github.com/julienschmidt/spinlock"
)
var (
mutex spinlock.Mutex
current = 0
result = make(map[int]string)
input int
err error
)
func main() {
if len(os.Args) >= 2 {
input, err = strconv.Atoi(os.Args[1])
}
if err != nil || input == 0 {
input = 15
}
var waitGroup sync.WaitGroup
waitGroup.Add(4)
go number(input, &waitGroup)
go fizzbuzz(input, &waitGroup)
go fizz(input, &waitGroup)
go buzz(input, &waitGroup)
waitGroup.Wait()
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
b := bufio.NewWriter(os.Stdout)
defer b.Flush()
for k := range sortMap(result) {
fmt.Fprintf(b, "Number: %d\t\tResult: %s\n", k, result[k])
}
}()
waitGroup.Wait()
}
func sortMap(input map[int]string) []int {
keys := make([]int, 0, len(result))
for k := range result {
keys = append(keys, k)
}
sort.Ints(keys)
return keys
}
func fizz(n int, waitGroup *sync.WaitGroup) {
defer waitGroup.Done()
for {
mutex.Lock()
if current > n {
mutex.Unlock()
return
}
if current%3 == 0 && current%5 != 0 {
result[current] = "Fizz"
current++
}
mutex.Unlock()
}
}
func buzz(n int, waitGroup *sync.WaitGroup) {
defer waitGroup.Done()
for {
mutex.Lock()
if current > n {
mutex.Unlock()
return
}
if current%3 != 0 && current%5 == 0 {
result[current] = "Buzz"
current++
}
mutex.Unlock()
}
}
func fizzbuzz(n int, waitGroup *sync.WaitGroup) {
defer waitGroup.Done()
for {
mutex.Lock()
if current > n {
mutex.Unlock()
return
}
if current%3 == 0 && current%5 == 0 {
result[current] = "FizzBuzz"
current++
}
mutex.Unlock()
}
}
func number(n int, waitGroup *sync.WaitGroup) {
for current <= n {
if current%3 != 0 && current%5 != 0 {
mutex.Lock()
result[current] = strconv.Itoa(current)
current++
mutex.Unlock()
}
}
waitGroup.Done()
}