Skip to content

Instantly share code, notes, and snippets.

@zacharysyoung
Last active July 27, 2020 21:35
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 zacharysyoung/e93862dc9a78cfe2ae964cdca71f38f0 to your computer and use it in GitHub Desktop.
Save zacharysyoung/e93862dc9a78cfe2ae964cdca71f38f0 to your computer and use it in GitHub Desktop.
'The Go Programming Language', Exercise 1.4
// Exercise 1.4 from 'The Go Programming Language', by A Donovan and
// B Kernigham
//
// Zach Young
// 27 May, 2019
//
//Dup2 prints the count and text of lines that appear more than once
//in the input. It reads from stdin or from a list of named files.
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
counts := make(map[string]map[string]int)
files := os.Args[1:]
if len(files) == 0 {
countLines(os.Stdin, counts, "Stdin")
} else {
for _, arg := range files {
f, err := os.Open(arg)
if err != nil {
fmt.Fprintf(os.Stderr, "dup: %v\n", err)
continue
}
countLines(f, counts, arg)
f.Close()
}
}
for line, nameCount := range counts {
n := 0
names, sep := "", ""
for name, count := range nameCount {
names += sep + name + "[" + strconv.Itoa(count) + "]"
sep = " "
n += count
}
if n > 1 {
fmt.Printf("%d\t%s\t(%s)\n", n, line, names)
}
}
}
func countLines(f *os.File, counts map[string]map[string]int, name string) {
input := bufio.NewScanner(f)
for input.Scan() {
line := input.Text()
if counts[line] == nil {
counts[line] = make(map[string]int)
}
counts[line][name]++
}
// NOTE: ignoring potential errors from input.Err()
}
aaa
aaa
aaa
aaa
bbb
bbb
zzz
xxx
xxx
xxx
bbb
bbb
bbb
bbb
bbb
zzz
zzz
zzz
zzz
zzz
zzz
zzz
xxx
xxx
xxx
xxx
xxx
yyy
yyy
yyy
yyy
yyy
$ ./main dup*.txt | sort
4 aaa (dup1.txt[4])
5 yyy (dup3.txt[5])
7 bbb (dup1.txt[2] dup2.txt[5])
8 xxx (dup2.txt[3] dup3.txt[5])
8 zzz (dup1.txt[1] dup2.txt[3] dup3.txt[4])
$ cat *.txt | ./main
8 zzz (Stdin[8])
8 xxx (Stdin[8])
5 yyy (Stdin[5])
4 aaa (Stdin[4])
7 bbb (Stdin[7])
@dbgoytia
Copy link

Hey man! I found your answer, pretty neat!
I made some changes of my own if you'd like to check: https://gist.github.com/ironknight78/082de37afffd13ad6df62a30f90bb262

@zacharysyoung
Copy link
Author

zacharysyoung commented Jul 27, 2020

Hi, @ironknight78! Thanks for the message, I'm glad it caught your attention :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment