Skip to content

Commit

Permalink
...
Browse files Browse the repository at this point in the history
  • Loading branch information
mbraeutig committed May 1, 2020
1 parent a1a0cfb commit acffb2d
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
32 changes: 32 additions & 0 deletions ch1/exercise1.3/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package main

import (
"fmt"
"strings"
)

func main() {
}

func echo1(args []string) {
var s, sep string

for i := 0; i < len(args); i++ {
s += sep + args[i]
sep = " "
}
fmt.Println(s)
}

func echo2(args []string) {
s, sep := "", ""
for _, arg := range args[1:] {
s += sep + arg
sep = " "
}
fmt.Println(s)
}

func echo3(args []string) {
fmt.Println(strings.Join(args[1:], " "))
}
50 changes: 50 additions & 0 deletions ch1/exercise1.4/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/

// Dup2 prints the count and text of lines that appears more than once in the input
// It reads form stdin or from a list of named files.
package main

import (
"bufio"
"fmt"
"os"
)

func main() {
counts := make(map[string]int)
files := os.Args[1:]
if len(files) == 0 {
countLines(os.Stdin, counts)
} else {
for i, arg := range files {
f, err := os.Open(arg)
if err != nil {
fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
continue
}
fmt.Println("Filename:", files[i])
countLines(f, counts)
f.Close()
}
}
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}

// NOTE:
// A map is a reference to the data structure created by make.
// When a map is passed to a function, the function receives a copy of the reference,
// so any changes the called function makes to the underlying data structure
// will be visible through the caller ’s map reference too.
// In our example, the values inserted into the counts map by countLines are seen by main.
func countLines(f *os.File, counts map[string]int) {
input := bufio.NewScanner(f)
for input.Scan() {
counts[input.Text()]++
}
// NOTE: ignoring potential errors from input.err
}

0 comments on commit acffb2d

Please sign in to comment.