Skip to content

Instantly share code, notes, and snippets.

@dbgoytia
Last active July 26, 2020 23:09
Show Gist options
  • Save dbgoytia/082de37afffd13ad6df62a30f90bb262 to your computer and use it in GitHub Desktop.
Save dbgoytia/082de37afffd13ad6df62a30f90bb262 to your computer and use it in GitHub Desktop.
The Go Programming Language Exercise 1.4
aaa
aaa
aaa
aaa
aaa
bbb
ccc
aaa
ccc
ddd
ccc
ddd
xxx
xxx
yyy
yyy
yyy
yyy
yyy
www
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// Store the names of the files, and the words and times the owrd has repeated
// { word: {filename : times}}
counts := make(map[string]map[string]int)
files := os.Args[1:]
if len(files) == 0 {
countLines2(os.Stdin, counts, "os.Stdin")
} else {
for _, arg := range files {
f, err := os.Open(arg)
if err != nil {
fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
}
countLines2(f, counts, arg)
f.Close()
}
}
for line, filenames := range counts {
// Count the number of files in which a line appears in:
fileCount := len(filenames)
// Count total number of appearances
var total = 0
fmt.Printf("Found [%s] in [%d] files:\n", line, fileCount)
for name, count := range filenames {
fmt.Printf("\t%d appearances in %s\n", count, name)
total += count
}
fmt.Printf("\t->Total appearances: %d\n", total)
}
}
func countLines2(f *os.File, counts map[string]map[string]int, filename string) {
input := bufio.NewScanner(f)
for input.Scan() {
if counts[input.Text()] == nil {
counts[input.Text()] = make(map[string]int)
}
counts[input.Text()][filename]++
}
}
Found [aaa] in [2] files:
5 appearances in dup1.txt
1 appearances in dup2.txt
->Total appearances: 6
Found [bbb] in [1] files:
1 appearances in dup1.txt
->Total appearances: 1
Found [ccc] in [3] files:
1 appearances in dup3.txt
1 appearances in dup1.txt
1 appearances in dup2.txt
->Total appearances: 3
Found [ddd] in [2] files:
1 appearances in dup2.txt
1 appearances in dup3.txt
->Total appearances: 2
Found [xxx] in [2] files:
1 appearances in dup4.txt
1 appearances in dup3.txt
->Total appearances: 2
Found [yyy] in [1] files:
5 appearances in dup4.txt
->Total appearances: 5
Found [www] in [1] files:
1 appearances in dup4.txt
->Total appearances: 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment