Week 1 Days 1-4

This commit is contained in:
Meutel 2017-07-07 14:29:36 +02:00
commit 477a79264b
21 changed files with 714 additions and 0 deletions

30
.gitignore vendored Normal file
View File

@ -0,0 +1,30 @@
*.swp
*~
converter/converter
example-wordcount/example-wordcount
go-cat/go-cat
go-cp/go-cp
.git/hooks/post-update.sample
.git/hooks/pre-commit.sample
.git/hooks/prepare-commit-msg.sample
.git/hooks/applypatch-msg.sample
.git/hooks/pre-receive.sample
.git/hooks/pre-push.sample
.git/hooks/pre-applypatch.sample
.git/hooks/update.sample
.git/hooks/commit-msg.sample
.git/hooks/pre-rebase.sample
fizzbuzz/fizzbuzz
go-hello/go-hello
example-file/example-file
w1d1ex31/w1d1ex31
sandbox/sandbox
example-center/example-center
shape/shape
example-clumps/example-clumps
file-wordcount/example-wordcount
file-wordcount/file-wordcount
avatar/avatar
w1d2ex1/w1d2ex1
swap/swap
w1d1ex2/w1d1ex2

60
avatar/main.go Normal file
View File

@ -0,0 +1,60 @@
package main
import "fmt"
import "log"
import "os"
import "strings"
var users = map[string]map[string]string{
"meutel": map[string]string{
"avatar_url": "https://git.meutel.net/avatars/1",
"full_name": "Meutel",
},
"ARCHIVES": map[string]string{
"avatar_url": "https://git.meutel.net/avatars/2",
},
}
const defaultAvatar = "https://git.meutel.net/img/avatar_default.png"
func avatarUrl(username string) string {
if url, ok := users[username]["avatar_url"]; ok {
return url
} else {
return defaultAvatar
}
}
func fullName(username string) (string, bool) {
if user, ok := users[username]; ok {
if name, ok2 := user["full_name"]; ok2 {
return name, true
} else {
return username, true
}
} else {
return "Unknown", false
}
}
func main() {
if len(os.Args) < 2 {
log.Fatalln("Needs user name argument")
}
name := os.Args[1]
// avatarId := 1
html := `<!DOCTYPE html>
<html>
<head><title>Profile</title></head>
<body>
<h1>{{ name }}</h1>
<img src="{{ avatarUrl }}"/>
</body>
</html>`
full, exists := fullName(name)
if !exists {
fmt.Fprintln(os.Stderr, "Unknown user "+name)
}
html = strings.Replace(html, "{{ name }}", full, 1)
html = strings.Replace(html, "{{ avatarUrl }}", avatarUrl(name), 1)
fmt.Println(html)
}

76
converter/main.go Normal file
View File

@ -0,0 +1,76 @@
package main
import "fmt"
import "log"
import "os"
import "strconv"
import "strings"
const (
markerMiles = "mi"
markerKm = "km"
markerFeet = "ft"
markerMeter = "m"
MilesToKm float64 = 1.609344
FeetsToMeters float64 = 3.28084
)
var (
inUnit string
inVal float64
asMeter float64
err error
convVal float64
)
func main() {
if len(os.Args) < 3 {
log.Fatalln("Needs 2 arguments")
}
input := os.Args[1]
convTo := os.Args[2]
switch {
case strings.HasSuffix(input, markerKm):
inUnit = markerKm
case strings.HasSuffix(input, markerFeet):
inUnit = markerFeet
case strings.HasSuffix(input, markerMeter):
inUnit = markerMeter
case strings.HasSuffix(input, markerMiles):
inUnit = markerMiles
default:
log.Fatalln("Invalid input:", input)
}
inVal, err = strconv.ParseFloat(input[:len(input)-len(inUnit)], 64)
if err != nil {
log.Fatalln("Invalid input number", err)
}
switch inUnit {
case markerMiles:
asMeter = inVal * MilesToKm * 1000
case markerKm:
asMeter = inVal * 1000
case markerFeet:
asMeter = inVal * FeetsToMeters
case markerMeter:
asMeter = inVal
}
// fmt.Println(inVal, inUnit, asMeter, convTo)
switch convTo {
case markerMiles:
convVal = asMeter / (MilesToKm * 1000)
case markerKm:
convVal = asMeter / 1000
case markerFeet:
convVal = asMeter / FeetsToMeters
case markerMeter:
convVal = asMeter
default:
log.Fatalln("Invalid unit: " + convTo)
}
fmt.Printf("%.2f%s\n", convVal, convTo)
}

46
example-center/main.go Normal file
View File

@ -0,0 +1,46 @@
package main
import "fmt"
func average(nums []float64) float64 {
if len(nums) == 0 {
return 0
}
var sum float64
for _, i := range nums {
sum += i
}
return sum / float64(len(nums))
}
func filter(nums []float64, comp func(float64, float64) bool) []float64 {
if len(nums) == 0 {
return make([]float64, 0)
}
val, idxVal := nums[0], 0
for idx, num := range nums {
if comp(num, val) {
val, idxVal = num, idx
}
}
nums = append(nums[:idxVal], nums[idxVal+1:]...)
return nums
}
func centeredAverage(nums ...float64) float64 {
nums = filter(nums, func(a float64, b float64) bool {
return a > b
})
nums = filter(nums, func(a float64, b float64) bool {
return a < b
})
return average(nums)
}
func main() {
fmt.Println(centeredAverage())
fmt.Println(centeredAverage(1, 2, 3, 4, 100))
fmt.Println(centeredAverage(1))
fmt.Println(centeredAverage(1, 1))
fmt.Println(centeredAverage(1, 1, 1))
}

26
example-clumps/main.go Normal file
View File

@ -0,0 +1,26 @@
package main
import "fmt"
func countClumps(sl []int) uint {
var count uint
var prevs [2]int
for idx, val := range sl {
if (idx == 1 && val == prevs[1]) || (idx > 1 && val == prevs[1] && prevs[0] != prevs[1]) {
count++
}
prevs[0] = prevs[1]
prevs[1] = val
}
return count
}
func main() {
fmt.Println(countClumps([]int{2, 2, 2, 3, 4, 4}))
fmt.Println(countClumps([]int{1, 1, 2, 1, 1}))
fmt.Println(countClumps([]int{1, 1, 1, 1, 1}))
fmt.Println(countClumps([]int{0, 1, 1, 1, 1}))
fmt.Println(countClumps([]int{0, 0}))
fmt.Println(countClumps([]int{0}))
fmt.Println(countClumps([]int{1, 1, 2, 3, 1, 4, 1, 1}))
}

32
example-file/main.go Normal file
View File

@ -0,0 +1,32 @@
package main
import "fmt"
import "io"
import "io/ioutil"
import "log"
import "os"
import "strings"
var err *error
func readMe(r io.Reader) {
content, err := ioutil.ReadAll(r)
if err != nil {
log.Fatalln(err)
}
fmt.Printf("%s\n", content)
}
func main() {
f, err := os.Open("/home/meutel/tmp/hello.txt")
if err != nil {
log.Fatalln(err)
}
defer f.Close()
fmt.Println(f.Name())
fmt.Println(f.Stat())
readMe(f)
strreader := strings.NewReader("c'est cool")
readMe(strreader)
}

20
example-wordcount/main.go Normal file
View File

@ -0,0 +1,20 @@
package main
import "fmt"
import "os"
import "strings"
func wc(text string) map[string]uint {
words := make(map[string]uint)
for _, word := range strings.Fields(text) {
words[word]++
}
return words
}
func main() {
input := strings.Join(os.Args[1:], " ")
fmt.Println(input)
fmt.Println(strings.Repeat("-", 80))
fmt.Println(wc(input))
}

35
file-wordcount/main.go Normal file
View File

@ -0,0 +1,35 @@
package main
import "fmt"
import "io"
import "io/ioutil"
import "log"
import "os"
import "strings"
func wc(r io.Reader) map[string]uint {
words := make(map[string]uint)
if text, err := ioutil.ReadAll(r); err != nil {
log.Fatalln(err)
} else {
for _, word := range strings.Fields(string(text)) {
words[word]++
}
}
return words
}
func openFile(path *string) *os.File {
f, err := os.Open(os.Args[1])
if err != nil {
log.Fatalln(err)
}
return f
}
func main() {
if len(os.Args) <= 1 {
log.Fatalln("Missing file")
}
f := openFile(&os.Args[1])
fmt.Println(wc(f))
}

19
fizzbuzz/main.go Normal file
View File

@ -0,0 +1,19 @@
package main
import "fmt"
func main() {
for i := 1; i <= 100; i++ {
mod3 := i % 3
mod5 := i % 5
if mod3+mod5 == 0 {
fmt.Println("FizzBuzz")
} else if mod3 == 0 {
fmt.Println("Fizz")
} else if mod5 == 0 {
fmt.Println("Buzz")
} else {
fmt.Println(i)
}
}
}

46
go-cat/main.go Normal file
View File

@ -0,0 +1,46 @@
package main
import "fmt"
import "io"
import "io/ioutil"
import "log"
import "os"
import "strings"
var err error
var reader io.Reader
func openFile(path *string) *os.File {
f, err := os.Open(os.Args[1])
if err != nil {
log.Fatalln(err)
}
return f
}
func readMe(r *io.Reader) {
if content, err := ioutil.ReadAll(*r); err != nil {
log.Fatalln(err)
} else {
fmt.Printf("%s", content)
}
}
func main() {
if len(os.Args) <= 1 {
var content string
if _, err := fmt.Scanln(&content); err != nil {
log.Fatalln(err)
}
reader = strings.NewReader(content)
} else {
readers := []io.Reader{}
for i := 1; i < len(os.Args); i++ {
f := openFile(&os.Args[i])
defer f.Close()
readers = append(readers, f)
}
reader = io.MultiReader(readers...)
}
readMe(&reader)
}

51
go-cp/main.go Normal file
View File

@ -0,0 +1,51 @@
package main
import "fmt"
import "os"
import "log"
import "io"
var err error
var from, to *os.File
const bufSize = 64 * 1024
func copyFile(src io.Reader, dst io.Writer) error {
buf := make([]byte, bufSize)
for {
n, er := src.Read(buf)
if er != nil || n == 0 {
if er != nil && er != io.EOF {
return fmt.Errorf("Read error: %v:", er)
}
break
}
_, wer := dst.Write(buf[:n])
if wer != nil {
return fmt.Errorf("Write error: %v:", wer)
}
}
return nil
}
func main() {
if len(os.Args) != 3 {
log.Fatalln("Usage: go-cp from to")
}
from, err = os.Open(os.Args[1])
if err != nil {
log.Fatalln("Error open", err)
}
defer from.Close()
to, err = os.Create(os.Args[2])
if err != nil {
log.Fatalln("Error open", err)
}
defer to.Close()
// err = copyFile(from, to)
_, err = io.Copy(from, to)
if err != nil {
log.Fatalln(err)
}
}

12
go-hello/half.txt Normal file
View File

@ -0,0 +1,12 @@
package main
import "fmt"
func half(i int) (int, bool) {
return i / 2, i%2 == 0
}
func main() {
fmt.Println(half(1))
fmt.Println(half(2))
}

12
go-hello/main.go Normal file
View File

@ -0,0 +1,12 @@
package main
import "fmt"
func visit(nums []int, callback func(...interface{}) (int, error)) {
for _, n := range nums {
callback(n)
}
}
func main() {
visit([]int{1, 2, 3, 4, 5}, fmt.Println)
}

16
go-hello/max.txt Normal file
View File

@ -0,0 +1,16 @@
package main
import "fmt"
func main() {
Max := func(nums ...int) int {
max := -1 << 63
for _, i := range nums {
if max < i {
max = i
}
}
return max
}
fmt.Println(Max(3, 2, 1))
}

21
go-hello/min_slice.txt Normal file
View File

@ -0,0 +1,21 @@
package main
import (
"fmt"
)
func main() {
x := []int{
48, 96, 86, 68,
57, 82, 63, 70,
37, 34, 83, 27,
19, 97, 9, 17,
}
min := x[0]
for _, i := range x {
if i < min {
min = i
}
}
fmt.Println(min)
}

32
go-hello/old Normal file
View File

@ -0,0 +1,32 @@
// doc package
package main
import (
"fmt"
"strconv"
"strings"
)
const unicode = "songe d'une nuit d'été"
func main() {
fmt.Println(strings.ToTitle(unicode))
fmt.Println(strings.ToUpper(unicode))
fmt.Println(strings.Replace(unicode, "été", "hiver", -1))
test := ""
//test := "0777"
fmt.Println(strconv.ParseInt(test, 8, 0))
fmt.Println(strconv.Quote(unicode))
sl := []int{1, 2, 3}
sl2 := append(sl, 4, 5)
sl[0] = 9
fmt.Println(sl)
fmt.Println(sl2)
sl3 := make([]int, 2)
copy(sl3, sl2[2:])
fmt.Println(sl3)
}

73
shape/main.go Normal file
View File

@ -0,0 +1,73 @@
package main
import "fmt"
import "math"
type Rectangle struct {
x1, y1, x2, y2 float64
}
func (r *Rectangle) length() float64 {
return distance(r.x1, r.y1, r.x1, r.y2)
}
func (r *Rectangle) width() float64 {
return distance(r.x1, r.y1, r.x2, r.y1)
}
func (r *Rectangle) area() float64 {
return r.length() * r.width()
}
func (r *Rectangle) perimeter() float64 {
return 2*r.length() + 2*r.width()
}
type Circle struct {
x float64
y float64
r float64
}
func (c *Circle) area() float64 {
return math.Pi * c.r * c.r
}
func (c *Circle) perimeter() float64 {
return 2 * math.Pi * c.r
}
type Shape interface {
area() float64
perimeter() float64
}
type MultiShape struct {
shapes []Shape
}
func (m *MultiShape) area() float64 {
var area float64
for _, s := range m.shapes {
area += s.area()
}
return area
}
func (m *MultiShape) perimeter() float64 {
var perimeter float64
for _, s := range m.shapes {
perimeter += s.perimeter()
}
return perimeter
}
func distance(x1, y1, x2, y2 float64) float64 {
a := x2 - x1
b := y2 - y1
return math.Sqrt(a*a + b*b)
}
func main() {
c := &Circle{x: 1, y: 1, r: 4}
r := &Rectangle{x2: 4, y2: 10}
ms := MultiShape{[]Shape{c, r}}
fmt.Println("Area", ms.area())
fmt.Println("Perimeter", ms.perimeter())
}

49
swap/main.go Normal file
View File

@ -0,0 +1,49 @@
package main
import "fmt"
func swap(x, y *int) {
*x, *y = *y, *x
/*
tmp := *x
*x = *y
*y = tmp
*/
}
func rotate(ptrs ...*int) {
if len(ptrs) == 0 {
return
}
tmp := *ptrs[0]
for i := 1; i < len(ptrs); i++ {
*ptrs[i-1] = *ptrs[i]
}
*ptrs[len(ptrs)-1] = tmp
}
func main() {
x := 1
y := 2
swap(&x, &y)
fmt.Println("x =", x)
fmt.Println("y =", y)
a := 1
b := 2
c := 3
rotate(&a, &b, &c)
fmt.Println("a =", a)
fmt.Println("b =", b)
fmt.Println("c =", c)
rotate(&a, &b, &c)
fmt.Println("a =", a)
fmt.Println("b =", b)
fmt.Println("c =", c)
rotate(&a, &b, &c)
fmt.Println("a =", a)
fmt.Println("b =", b)
fmt.Println("c =", c)
}

12
w1d1ex2/main.go Normal file
View File

@ -0,0 +1,12 @@
package main
import "fmt"
var (
input string
)
func main() {
fmt.Scanf("%s", &input)
fmt.Println("Hello ", input)
}

14
w1d1ex31/main.go Normal file
View File

@ -0,0 +1,14 @@
package main
import "fmt"
var input float32
const MilesToKm = 1.6
func main() {
fmt.Println("Enter miles:")
fmt.Scanf("%f", &input)
fmt.Println(input, " miles is about ", input*MilesToKm, " km")
}

32
w1d2ex1/main.go Normal file
View File

@ -0,0 +1,32 @@
package main
import "fmt"
import "os"
import "strconv"
var miles float64
const (
MilesToKm float64 = 1.609344
width = 20
titleMiles = "| Miles: "
titleKm = "| Km: "
)
func main() {
if miles, err := strconv.ParseFloat(os.Args[1], 64); err == nil {
fmtMiles := strconv.FormatFloat(miles, 'f', 2, 64)
fmtKm := strconv.FormatFloat(miles*MilesToKm, 'f', 2, 64)
fmt.Println("<!DOCTYPE html>")
fmt.Println("<html>")
fmt.Println(" <head><title>Miles to Kilometers</title></head>")
fmt.Println(" <body>")
fmt.Println(" <p>Miles:", fmtMiles, "</p>")
fmt.Println(" <p>Kilometers:", fmtKm, "</p>")
fmt.Println(" </body>")
fmt.Println("</html>")
} else {
panic(err)
}
}