restructure: arrays and slices

This commit is contained in:
Inanc Gumus
2019-01-29 19:43:12 +03:00
parent 096ac9c251
commit c43d152d33
108 changed files with 92 additions and 243 deletions

View File

@@ -1,38 +0,0 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
s "github.com/inancgumus/prettyslice"
)
func main() {
msg := []byte{'h', 'e', 'l', 'l', 'o'}
s.Show("msg", msg)
s.Show("msg[0:1]", msg[0:1])
s.Show("msg[0:2]", msg[0:2])
s.Show("msg[0:3]", msg[0:3])
s.Show("msg[0:4]", msg[0:4])
s.Show("msg[0:5]", msg[0:5])
// default indexes
s.Show("msg[0:]", msg[0:])
s.Show("msg[:5]", msg[:5])
s.Show("msg[:]", msg[:])
// error: beyond
// s.Show("msg", msg)[:6]
s.Show("msg[1:4]", msg[1:4])
s.Show("msg[1:5]", msg[1:5])
s.Show("msg[1:]", msg[1:])
s.Show("append(msg)", append(msg[:4], '!'))
}

View File

@@ -1,59 +0,0 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
s "github.com/inancgumus/prettyslice"
)
func main() {
// think of this as search results of a search engine.
// it could have been fetched from a database
items := []string{
"pacman",
"mario",
"tetris",
"doom",
"galaga",
"frogger",
"asteroids",
"simcity",
"metroid",
"defender",
"rayman",
"tempest",
"ultima",
}
s.MaxPerLine = 4
s.Show("All items", items)
top3 := items[:3]
s.Show("Top 3 items", top3)
l := len(items)
// you can use variables in a slice expression
last4 := items[l-4:]
s.Show("Last 4 items", last4)
// reslicing: slicing another sliced slice
mid := last4[1:3]
s.Show("Last4[1:3]", mid)
// the same elements can be in different indexes
// fmt.Println(items[9], last4[0])
// slicing returns a slice with the same type of the sliced slice
fmt.Printf("slicing : %T %[1]q\n", items[2:3])
// indexing returns a single element with the type of the indexed slice's element type
fmt.Printf("indexing: %T %[1]q\n", items[2])
}

View File

@@ -1,58 +0,0 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
s "github.com/inancgumus/prettyslice"
)
func main() {
// think of this as search results of a search engine.
// it could have been fetched from a database
items := []string{
"pacman",
"mario",
"tetris",
"doom",
"galaga",
"frogger",
"asteroids",
"simcity",
"metroid",
"defender",
"rayman",
"tempest",
"ultima",
}
// s.Show("0:4", items[0:4])
// s.Show("4:8", items[4:8])
// s.Show("8:12", items[8:12])
// s.Show("12:13", items[12:13])
// s.Show("12:14", items[12:14]) // error
l := len(items)
const pageSize = 4
for from := 0; from < l; from += pageSize {
to := from + pageSize
if to > l {
to = l
}
// fmt.Printf("%d:%d\n", from, to)
currentPage := items[from:to]
head := fmt.Sprintf("Page #%d", (from/pageSize)+1)
s.Show(head, currentPage)
}
}

View File

@@ -1,26 +0,0 @@
# The Brief Anatomy of a PNG image
```
The first 24 bytes:
PNG HEADER:
╔═════╗╔════╗╔════╗╔════╗╔════╗╔════╗╔════╗╔════╗
║ 137 ║║ 80 ║║ 78 ║║ 71 ║║ 13 ║║ 10 ║║ 26 ║║ 10 ║
╚═════╝╚════╝╚════╝╚════╝╚════╝╚════╝╚════╝╚════╝
0 1 2 3 4 5 6 7
CHUNK LENGTH CHUNK TYPE (IHDR)
╔═══╗╔═══╗╔═══╗╔════╗╔════╗╔════╗╔════╗╔════╗
║ 0 ║║ 0 ║║ 0 ║║ 13 ║║ 73 ║║ 72 ║║ 68 ║║ 82 ║
╚═══╝╚═══╝╚═══╝╚════╝╚════╝╚════╝╚════╝╚════╝
8 9 10 11 12 13 14 15
( Unsigned 32-bit integers )
WIDTH HEIGHT
╔═══╗╔═══╗╔═══╗╔════╗╔═══╗╔═══╗╔═══╗╔════╗
║ 0 ║║ 0 ║║ 2 ║║ 76 ║║ 0 ║║ 0 ║║ 3 ║║ 32 ║
╚═══╝╚═══╝╚═══╝╚════╝╚═══╝╚═══╝╚═══╝╚════╝
16 17 18 19 20 21 22 23
... Other bytes in the png image ...
```

View File

@@ -0,0 +1 @@
learngoprogramming.com

View File

@@ -0,0 +1 @@
learngoprogramming.com

View File

@@ -0,0 +1 @@
learngoprogramming.com

View File

@@ -0,0 +1,35 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
args := os.Args[1:]
if len(args) == 0 {
fmt.Println("Provide a directory")
return
}
files, err := ioutil.ReadDir(args[0])
if err != nil {
fmt.Println(err)
return
}
for _, file := range files {
if file.Size() == 0 {
name := file.Name()
fmt.Println(name)
}
}
}

View File

@@ -0,0 +1 @@
learngoprogramming.com

View File

@@ -0,0 +1 @@
learngoprogramming.com

View File

@@ -0,0 +1 @@
learngoprogramming.com

View File

@@ -0,0 +1,50 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
args := os.Args[1:]
if len(args) == 0 {
fmt.Println("Provide a directory")
return
}
files, err := ioutil.ReadDir(args[0])
if err != nil {
fmt.Println(err)
return
}
var names []byte
for _, file := range files {
if file.Size() == 0 {
name := file.Name()
names = append(names, name...)
names = append(names, '\n')
}
}
err = ioutil.WriteFile("out.txt", names, 0644)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%s", names)
}
// See: https://www.tutorialspoint.com/unix/unix-file-permission.htm
// See: http://permissions-calculator.org/

View File

@@ -0,0 +1,42 @@
package main
// ---------------------------------------------------------
// EXERCISE: Sort to a file
//
// 1. Get arguments from command-line
//
// 2. Sort them
//
// 3. Write the sorted slice to a file
//
//
// EXPECTED OUTPUT
//
// go run main.go
// Send me some items and I will sort them
//
// go run main.go orange banana apple
//
// cat sorted.txt
// apple
// banana
// orange
//
//
// HINTS
//
// ONLY READ THIS IF YOU GET STUCK
//
// Below, []string means string slice, []byte means byte slice.
//
// + You can use the os.Args[1:] to get a []string
// + Then you can sort it using sort.Strings
// + Use ioutil.WriteFile to write to a file.
// + But you need to convert []string to []byte to be able to
// write it to a file using the ioutil.WriteFile.
// + To do that, create a new []byte and append the elements of your
// []string.
// ---------------------------------------------------------
func main() {
}

View File

@@ -0,0 +1,37 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"io/ioutil"
"os"
"sort"
)
func main() {
items := os.Args[1:]
if len(items) == 0 {
fmt.Println("Send me some items and I will sort them")
return
}
sort.Strings(items)
var data []byte
for _, s := range items {
data = append(data, s...)
data = append(data, '\n')
}
err := ioutil.WriteFile("sorted.txt", data, 0644)
if err != nil {
fmt.Println(err)
return
}
}

View File

@@ -0,0 +1,70 @@
package main
import (
"fmt"
"io/ioutil"
"os"
"sort"
)
// ---------------------------------------------------------
// EXERCISE: Sort to a file with ordinals
//
// Use the previous exercise: Append #4
//
// This time, print the sorted items with ordinals
// (see the expected output)
//
//
// EXPECTED OUTPUT
//
// go run main.go
// Send me some items and I will sort them
//
// go run main.go orange banana apple
//
// cat sorted.txt
// 1. apple
// 2. banana
// 3. orange
//
//
// HINTS
//
// ONLY READ THIS IF YOU GET STUCK
//
// + You can use strconv.AppendInt function to append an int
// to a byte slice. strconv contains a lot of functions for appending
// other basic types as well.
//
// + You can append individual characters to a byte slice using
// rune literals:
//
// var slice []byte
// slice = append(slice, 'h', 'i', ' ', '!')
// fmt.Printf("%s\n", slice)
//
// Above code prints: hi !
// ---------------------------------------------------------
func main() {
items := os.Args[1:]
if len(items) == 0 {
fmt.Println("Send me some items and I will sort them")
return
}
sort.Strings(items)
var data []byte
for _, s := range items {
data = append(data, s...)
data = append(data, '\n')
}
err := ioutil.WriteFile("sorted.txt", data, 0644)
if err != nil {
fmt.Println(err)
return
}
}

View File

@@ -0,0 +1,40 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"io/ioutil"
"os"
"sort"
"strconv"
)
func main() {
items := os.Args[1:]
if len(items) == 0 {
fmt.Println("Send me some items and I will sort them")
return
}
sort.Strings(items)
var data []byte
for i, s := range items {
data = strconv.AppendInt(data, int64(i+1), 10)
data = append(data, '.', ' ')
data = append(data, s...)
data = append(data, '\n')
}
err := ioutil.WriteFile("sorted.txt", data, 0644)
if err != nil {
fmt.Println(err)
return
}
}

View File

@@ -0,0 +1,56 @@
package main
// ---------------------------------------------------------
// EXERCISE: Print the directories
//
// Create a program that can get multiple directory paths from
// the command-line, and prints only their subdirectories into a
// file named: dirs.txt
//
//
// 1. Get the directory paths from command-line
//
// 2. Append the names of subdirectories inside each directory
// to a byte slice
//
// 3. Write that byte slice to dirs.txt file
//
//
// EXPECTED OUTPUT
//
// go run main.go
// Please provide directory paths
//
// go run main.go dir/ dir2/
//
// cat dirs.txt
//
// dir/
// subdir1/
// subdir2/
//
// dir2/
// subdir1/
// subdir2/
// subdir3/
//
//
// HINTS
//
// ONLY READ THIS IF YOU GET STUCK
//
// + Get all the files in a directory using ioutil.ReadDir
// (A directory is also a file)
//
// + You can use IsDir method of a FileInfo value to detect
// whether a file is a directory or not: go doc os.FileInfo.IsDir
//
// + You can use '\t' escape sequence for indenting the subdirs.
//
// + You can find a sample directory structure under:
// solution/ directory
//
// ---------------------------------------------------------
func main() {
}

View File

@@ -0,0 +1,4 @@
*
!subdir1
!subdir2
!.gitignore

View File

@@ -0,0 +1,5 @@
*
!subdir1
!subdir2
!subdir3
!.gitignore

View File

@@ -0,0 +1,9 @@
dir/
subdir1/
subdir2/
dir2/
subdir1/
subdir2/
subdir3/

View File

@@ -0,0 +1,51 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
paths := os.Args[1:]
if len(paths) == 0 {
fmt.Println("Please provide directory paths")
return
}
var dirs []byte
for _, dir := range paths {
files, err := ioutil.ReadDir(dir)
if err != nil {
fmt.Println(err)
return
}
dirs = append(dirs, dir...)
dirs = append(dirs, '\n')
for _, file := range files {
if file.IsDir() {
dirs = append(dirs, '\t')
dirs = append(dirs, file.Name()...)
dirs = append(dirs, '/', '\n')
}
}
dirs = append(dirs, '\n')
}
err := ioutil.WriteFile("dirs.txt", dirs, 0644)
if err != nil {
fmt.Println(err)
return
}
}

View File

@@ -0,0 +1,7 @@
# File Append Exercises
1. **[Sort and write items to a file](https://github.com/inancgumus/learngo/tree/master/15-slices/19-empty-file-finder-project/exercises/1-sort-to-a-file)**
2. **[Sort and write items to a file with their ordinals](https://github.com/inancgumus/learngo/tree/master/15-slices/19-empty-file-finder-project/exercises/2-sort-to-a-file)**
3. **[Find and write the names of subdirectories to a file](https://github.com/inancgumus/learngo/tree/master/15-slices/19-empty-file-finder-project/exercises/3-print-directories)**

View File

@@ -4,14 +4,14 @@
The first 24 bytes:
+=================================+
| PNG Header | 8 bytes | -> 137 80 78 71 13 10 26 10
| PNG Header | 8 bytes | -> 89 50 4e 47 0d 0a 1a 0a
+---------------------+-----------+
| IHDR Chunk Header | |
| Chunk Length | 4 bytes | -> The length of the IHDR Chunk Data
| Chunk Type | 4 bytes | -> 73 72 68 82
| Chunk Type | 4 bytes | -> 49 48 44 52
+---------------------+-----------+
| IHDR Chunk Data | |
| Width | 4 bytes | -> Unsigned 32-bit integer
| Height | 4 bytes | -> Unsigned 32-bit integer
| Width | 4 bytes | -> uint32 — big endian
| Height | 4 bytes | -> uint32 — big endian
+=================================+
```

View File

@@ -0,0 +1,26 @@
# The Brief Anatomy of a PNG image
```
The first 24 bytes:
(all numbers are uint32 big-endian)
PNG HEADER
╔════╗╔════╗╔════╗╔════╗╔════╗╔════╗╔════╗╔════╗
║ 89 ║║ 50 ║║ 4e ║║ 47 ║║ 0d ║║ 0a ║║ 1a ║║ 0a ║
╚════╝╚════╝╚════╝╚════╝╚════╝╚════╝╚════╝╚════╝
0 1 2 3 4 5 6 7
CHUNK LENGTH CHUNK TYPE (IHDR)
╔════╗╔════╗╔════╗╔════╗╔════╗╔════╗╔════╗╔════╗
║ 00 ║║ 00 ║║ 00 ║║ 0d ║║ 49 ║║ 48 ║║ 44 ║║ 52 ║
╚════╝╚════╝╚════╝╚════╝╚════╝╚════╝╚════╝╚════╝
8 9 10 11 12 13 14 15
WIDTH HEIGHT
╔════╗╔════╗╔════╗╔════╗╔════╗╔════╗╔════╗╔════╗
║ 00 ║║ 00 ║║ 02 ║║ 4c ║║ 00 ║║ 00 ║║ 03 ║║ 20 ║
╚════╝╚════╝╚════╝╚════╝╚════╝╚════╝╚════╝╚════╝
16 17 18 19 20 21 22 23
... rest of the bytes in the png image ...
```

View File

Before

Width:  |  Height:  |  Size: 80 B

After

Width:  |  Height:  |  Size: 80 B

View File

Before

Width:  |  Height:  |  Size: 66 KiB

After

Width:  |  Height:  |  Size: 66 KiB

View File

@@ -6,16 +6,10 @@ import (
"fmt"
"io/ioutil"
"os"
ps "github.com/inancgumus/prettyslice"
"runtime"
)
func main() {
var (
pngHeader = [...]byte{137, 80, 78, 71, 13, 10, 26, 10}
ihdrChunkType = [...]byte{73, 72, 68, 82}
)
args := os.Args[1:]
if len(args) == 0 {
fmt.Println("run with a PNG file")
@@ -31,10 +25,19 @@ func main() {
return
}
// limit the capacity to prevent the errors downward
// 'cause we only need the first 24 bytes
img = append([]byte(nil), img[:24]...)
img = img[:24:24]
// ps.Show("first 24 bytes", img)
// s.PrintBacking = true
// s.MaxPerLine = 8
// s.MaxElements = 24
// s.PrintBytesHex = true
// s.Show("first 24 bytes", img)
var (
pngHeader = [...]byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a}
ihdrChunkType = [...]byte{0x49, 0x48, 0x44, 0x52}
)
// ------------------------------------------
// Read the PNG header
@@ -78,9 +81,9 @@ func main() {
binary.BigEndian.Uint32(ihdr[4:8]))
}
func init() {
ps.PrintBacking = true
ps.PrettyByteRune = false
ps.MaxPerLine = 8
ps.MaxElements = 32
func report() {
var m runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&m)
fmt.Printf(" > Memory Usage: %v KB\n", m.Alloc/1024)
}