Skip to content

Instantly share code, notes, and snippets.

@k4rtik
Created November 27, 2015 04:27
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 k4rtik/a745cee7975da16af4d0 to your computer and use it in GitHub Desktop.
Save k4rtik/a745cee7975da16af4d0 to your computer and use it in GitHub Desktop.
One solution to Exercise 1.4 in GoPL
package main
import (
"bufio"
"fmt"
"os"
)
type LnFile struct {
Count int
Filenames []string
}
func main() {
counts := make(map[string]*LnFile)
files := os.Args[1:]
if len(files) == 0 {
countLines(os.Stdin, counts)
} else {
for _, arg := range files {
f, err := os.Open(arg)
if err != nil {
fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
continue
}
countLines(f, counts)
f.Close()
}
}
for line, n := range counts {
if n.Count > 1 {
fmt.Printf("%d %v\n%s\n", n.Count, n.Filenames, line)
}
}
}
func countLines(f *os.File, counts map[string]*LnFile) {
input := bufio.NewScanner(f)
for input.Scan() {
key := input.Text()
_, ok := counts[key]
if ok {
counts[key].Count++
counts[key].Filenames = append(counts[key].Filenames, f.Name())
} else {
counts[key] = new(LnFile)
counts[key].Count = 1
counts[key].Filenames = append(counts[key].Filenames, f.Name())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment