working on chapter 1 exercises

This commit is contained in:
Derek McQuay 2015-12-03 18:29:13 -08:00
parent 676fe080a4
commit 2f004582fc
5 changed files with 112 additions and 0 deletions

12
ch1/1_1.go Normal file
View File

@ -0,0 +1,12 @@
package main
import (
"fmt"
"os"
"strings"
)
func main() {
fmt.Printf("command: %s\n", os.Args[0])
fmt.Printf("args: %s\n", strings.Join(os.Args[1:], " "))
}

19
ch1/1_2.go Normal file
View File

@ -0,0 +1,19 @@
package main
import (
"fmt"
"os"
"strings"
)
func main() {
fmt.Printf("command: %s\n", os.Args[0])
fmt.Printf("args: %s\n", strings.Join(os.Args[1:], " "))
str := ""
deli := " "
for i, j := range os.Args[1:] {
str += fmt.Sprintf("index: %d value: %s", i, j)
str += deli
}
fmt.Println(str)
}

33
ch1/1_3.go Normal file
View File

@ -0,0 +1,33 @@
package main
import (
"fmt"
"os"
"strings"
"time"
)
func usingJoin() {
fmt.Println(strings.Join(os.Args[1:], " "))
}
func forLoop() {
s, sep := "", " "
for _, i := range os.Args[1:] {
s += i
s += sep
}
fmt.Println(s)
}
func main() {
start := time.Now()
forLoop()
t1 := time.Since(start)
fmt.Println("for loop: ", t1)
start = time.Now()
usingJoin()
t2 := time.Since(start)
fmt.Println("using join: ", t2)
fmt.Println("Δ", t1-t2)
}

37
ch1/dup2.go Normal file
View File

@ -0,0 +1,37 @@
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
counts := make(map[string]int)
file := os.Args[1:]
if len(file) == 0 {
countLines(os.Stdin, counts)
} else {
for _, i := range file {
f, err := os.Open(i)
if err != nil {
log.Print(err)
}
countLines(f, counts)
f.Close()
}
}
for lines, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, lines)
}
}
}
func countLines(f *os.File, counts map[string]int) {
input := bufio.NewScanner(f)
for input.Scan() {
counts[input.Text()]++
}
}

11
ch1/echo.go Normal file
View File

@ -0,0 +1,11 @@
package main
import (
"fmt"
"os"
"strings"
)
func main() {
fmt.Println(strings.Join(os.Args[1:], " "))
}