-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathq2.go
45 lines (41 loc) · 1.24 KB
/
q2.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
package cos418_hw1_1
import (
"bufio"
"io"
"strconv"
)
// Sum numbers from channel `nums` and output sum to `out`.
// You should only output to `out` once.
// Do NOT modify function signature.
func sumWorker(nums chan int, out chan int) {
// TODO: implement me
// HINT: use for loop over `nums`
}
// Read integers from the file `fileName` and return sum of all values.
// This function must launch `num` go routines running
// `sumWorker` to find the sum of the values concurrently.
// You should use `checkError` to handle potential errors.
// Do NOT modify function signature.
func sum(num int, fileName string) int {
// TODO: implement me
// HINT: use `readInts` and `sumWorkers`
// HINT: used buffered channels for splitting numbers between workers
return 0
}
// Read a list of integers separated by whitespace from `r`.
// Return the integers successfully read with no error, or
// an empty slice of integers and the error that occurred.
// Do NOT modify this function.
func readInts(r io.Reader) ([]int, error) {
scanner := bufio.NewScanner(r)
scanner.Split(bufio.ScanWords)
var elems []int
for scanner.Scan() {
val, err := strconv.Atoi(scanner.Text())
if err != nil {
return elems, err
}
elems = append(elems, val)
}
return elems, nil
}