Compare commits

...

1 Commits
master ... sm

Author SHA1 Message Date
Stephen McQuay 0052da8e97
solved 1.4 2016-07-28 00:21:00 -07:00
1 changed files with 51 additions and 0 deletions

51
ch1/ex1.4/main.go Normal file
View File

@ -0,0 +1,51 @@
// ex1.4 solves exercise 1.4
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
counts := make(map[string]int)
files := make(map[string]map[string]bool)
inputs := os.Args[1:]
if len(inputs) == 0 {
countLines(os.Stdin, counts, files)
} else {
for _, arg := range inputs {
f, err := os.Open(arg)
if err != nil {
fmt.Fprintf(os.Stderr, "ex1.4: %v\n", err)
continue
}
if err := countLines(f, counts, files); err != nil {
panic(err)
}
f.Close()
}
}
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%q\n", n, line)
for file := range files[line] {
fmt.Printf("\tin %q\n", file)
}
}
}
}
func countLines(f *os.File, counts map[string]int, files map[string]map[string]bool) error {
input := bufio.NewScanner(f)
for input.Scan() {
line := input.Text()
counts[line]++
if _, ok := files[line]; !ok {
files[line] = make(map[string]bool)
}
files[line][f.Name()] = true
}
return input.Err()
}