Skip to content

Instantly share code, notes, and snippets.

@fstab
Last active March 28, 2017 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fstab/3ab5e26a76e62112caf628317afff3b5 to your computer and use it in GitHub Desktop.
Save fstab/3ab5e26a76e62112caf628317afff3b5 to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
file, err := os.Open(os.Args[1])
if err != nil {
fmt.Fprintf(os.Stderr, "failed to open test.medium: %v\n", err)
os.Exit(-1)
}
scanner := bufio.NewScanner(file)
nLines := 0
scanner.Scan()
nCols := len(strings.Split(scanner.Text(), ","))
sums := make([]int, nCols)
for scanner.Scan() {
values := strings.Split(scanner.Text(), ",")
for i := 0; i < len(sums); i++ {
nLines++
intVal, err := strconv.Atoi(values[i])
if err != nil {
fmt.Fprintf(os.Stderr, "invalid number: %v\n", values[i])
}
sums[i] += intVal
}
}
for _, arg := range os.Args[2:] {
argTokens := strings.Split(arg, "=")
colNumInt, err := strconv.Atoi(argTokens[0])
if err != nil {
fmt.Fprintf(os.Stderr, "syntax error\n")
}
switch argTokens[1] {
case "MEAN":
fmt.Printf("mean[%v]: %v\n", colNumInt, sums[colNumInt]/nLines)
case "SUM":
fmt.Printf("sum[%v]: %v\n", colNumInt, sums[colNumInt])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment