Skip to content

Instantly share code, notes, and snippets.

@rohanthewiz
Created March 16, 2017 17:44
Show Gist options
  • Save rohanthewiz/84a12e7ea7e451cb7b0f9585a43de1b6 to your computer and use it in GitHub Desktop.
Save rohanthewiz/84a12e7ea7e451cb7b0f9585a43de1b6 to your computer and use it in GitHub Desktop.
Golang: Sum, sort, and print values by User from data given in a file
package main
import (
"os"
"fmt"
"io/ioutil"
"strings"
"regexp"
"strconv"
"sort"
)
func main() {
file, err := os.Open("users.txt")
if err != nil {
fmt.Errorf("Could not open input file")
}
data, err := ioutil.ReadAll(file)
if err != nil {
fmt.Errorf("Unable to read file")
}
user_times := map[string]int{}
reg := regexp.MustCompile(`^\*?\s*(\w+) (\d+)`)
keys := []string{}
for _, line := range strings.Split(string(data), "\n") {
matches := reg.FindStringSubmatch(line)
if len(matches) >= 3 { // whole string + groups
if _, ok := user_times[matches[1]]; !ok {
user_times[matches[1]] = 0
keys = append(keys, matches[1])
}
user_time, err := strconv.Atoi(matches[2])
if err != nil {
fmt.Errorf("Error converting '%s'", matches[2])
}
user_times[matches[1]] += user_time
}
}
sort.Strings(keys)
for _, key := range keys {
fmt.Println(key,":", user_times[key])
}
}
// Users.txt will contain this data listed here for convenience
var file_data string = `
# Format: <user> <time>
# Asterisk: secure connection used.
Alice 13
John 440
Bob 2
Carl 49
* Peter 90
Alice 219
Bob 8
Alice 72
* Jim 1
Peter 97
Jim 199
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment