add: slice internals exercises

This commit is contained in:
Inanc Gumus
2019-03-04 20:30:18 +03:00
parent fe38be1025
commit 2c7ee6ebf5
14 changed files with 598 additions and 42 deletions

View File

@ -0,0 +1,109 @@
package main
import "fmt"
// ---------------------------------------------------------
// EXERCISE: Observe the length and capacity
//
// Follow the instructions inside the code below to
// gain more intuition about the length and capacity of a slice.
//
// ---------------------------------------------------------
func main() {
// --- #1 ---
// 1. create a new slice named: games
//
// 2. print the length and capacity of the games slice
//
// 3. comment out the games slice
// then declare it as an empty slice
//
// 4. print the length and capacity of the games slice
//
// 5. append the elements: "pacman", "mario", "tetris", "doom"
//
// 6. print the length and capacity of the games slice
//
// 7. comment out everything
//
// 8. declare it again using a slice literal
// (use the same elements from step 3)
// --- #2 ---
// 1. use a loop from 0 to 4 to slice the games slice, element by element.
//
// 2. print its length and capacity along the way (in the loop).
fmt.Println()
// for ... {
// fmt.Printf("games[:%d]'s len: %d cap: %d\n", ...)
// }
// --- #3 ---
// 1. slice the games slice up to zero element
// (save the result to a new slice named: "zero")
//
// 2. print the games and the new slice's len and cap
//
// 3. append a new element to the new slice
//
// 4. print the new slice's lens and caps
//
// 5. repeat the last two steps 5 times (use a loop)
//
// 6. notice the growth of the capacity after the 5th append
//
// Use this slice's elements to append to the new slice:
// []string{"ultima", "dagger", "pong", "coldspot", "zetra"}
fmt.Println()
// zero := ...
// fmt.Printf("games's len: %d cap: %d\n", ...)
// fmt.Printf("zero's len: %d cap: %d\n", ...)
// for ... {
// ...
// fmt.Printf("zero's len: %d cap: %d\n", ...)
// }
// --- #4 ---
// using a range loop, slice the zero slice element by element,
// and print its length and capacity along the way.
//
// observe that, the range loop only loops for the length, not the cap.
fmt.Println()
// for ... {
// s := zero[:n]
// fmt.Printf("zero[:%d]'s len: %d cap: %d\n", ...)
// }
// --- #5 ---
// 1. do the 3rd step above again but this time, start by slicing
// the zero slice up to its capacity (use the cap function).
//
// 2. print the elements of the zero slice in the loop.
fmt.Println()
// zero = ...
// for ... {
// fmt.Printf("zero[:%d]'s len: %d cap: %d - %q\n", ...)
// }
// --- #6 ---
// 1. change the one of the elements of the zero slice
//
// 2. change the same element of the games slice
//
// 3. print the games and the zero slices
//
// 4. observe that they don't have the same backing array
fmt.Println()
// ...
// fmt.Printf("zero : %q\n", zero)
// fmt.Printf("games : %q\n", games)
// --- #7 ---
// try to slice the games slice beyond its capacity
}

View File

@ -0,0 +1,76 @@
// 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"
func main() {
// --- #1 ---
// var games []string
// fmt.Printf("games's len : %d cap: %d\n", len(games), cap(games))
// games := []string{}
// fmt.Printf("games's len : %d cap: %d\n", len(games), cap(games))
// games = append(games, "pacman", "mario", "tetris", "doom")
// fmt.Printf("games's len : %d cap: %d\n", len(games), cap(games))
games := []string{"pacman", "mario", "tetris", "doom"}
fmt.Printf("games's len : %d cap: %d\n", len(games), cap(games))
// --- #2 ---
fmt.Println()
for i := 0; i <= len(games); i++ {
s := games[:i]
fmt.Printf("games[:%d]'s len: %d cap: %d\n", i, len(s), cap(s))
}
// --- #3 ---
fmt.Println()
zero := games[:0]
fmt.Printf("games's len: %d cap: %d\n", len(games), cap(games))
fmt.Printf("zero's len: %d cap: %d\n", len(zero), cap(zero))
for _, v := range []string{"ultima", "dagger", "pong", "coldspot", "zetra"} {
zero = append(zero, v)
fmt.Printf("zero's len: %d cap: %d\n", len(zero), cap(zero))
}
// --- #4 ---
fmt.Println()
for n := range zero {
s := zero[:n]
fmt.Printf("zero[:%d]'s len: %d cap: %d\n", n, len(s), cap(s))
}
// --- #5 ---
fmt.Println()
zero = zero[:cap(zero)]
for n := range zero {
s := zero[:n]
fmt.Printf("zero[:%d]'s len: %d cap: %d - %q\n", n, len(s), cap(s), s)
}
// --- #6 ---
fmt.Println()
zero[0] = "command & conquer"
games[0] = "red alert"
fmt.Printf("zero : %q\n", zero)
fmt.Printf("games : %q\n", games)
// --- #7 ---
// uncomment and see the error.
// _ = games[:cap(games)+1]
// or:
// _ = games[:5]
}

View File

@ -0,0 +1,34 @@
package main
// ---------------------------------------------------------
// EXERCISE: Observe the capacity growth
//
// Write a program that loops 10 million times to append an element
// to a slice, on each step of the loop. Observe the capacity.
//
//
// STEPS
//
// 1. Create a nil slice
//
// 2. Loop 10e6 times
//
// 3. On each loop step: Append an element to the slice
//
// 4. Only print the length and capacity of the slice everytime
// the capacity changes.
//
// 5. Print also the growth rate by calculating the previous and
// the current capacity.
//
//
// EXPECTED OUTPUT
//
// len:0 cap:0 growth:NaN
// len:1 cap:1 growth:+Inf
// len:2 cap:2 growth:2.00
// ... and so on.
//
// ---------------------------------------------------------
func main() {}

View File

@ -0,0 +1,29 @@
// 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"
func main() {
var (
nums []int
oldCap float64
)
for len(nums) < 10e6 {
c := float64(cap(nums))
if c == 0 || c != oldCap {
fmt.Printf("len:%-15d cap:%-15g growth:%-15.2f\n",
len(nums), c, c/oldCap)
}
oldCap = c
nums = append(nums, 1)
}
}

View File

@ -0,0 +1,45 @@
package main
import (
"fmt"
"strings"
)
// ---------------------------------------------------------
// EXERCISE: Correct the lyric
//
// You have a slice of lyrics data of Beatles' awesome
// song: Yesterday. Your goal is putting the words into
// correct positions.
//
//
// STEPS
//
// 1. Prepend "yesterday" to the `lyric` slice.
//
// 2. Put the words to the correct position in the `lyric` slice.
//
// 3. Print the `lyric` slice.
//
//
// EXPECTED OUTPUT
//
// [yesterday all my troubles seemed so far away now it looks as though they are here to stay oh i believe in yesterday]
//
//
// BONUS
//
// . Think about when does the append allocates a new backing array.
// . Then check whether your conclusions are true or not.
// . You can use the prettyslice package to check the backing array.
//
// ---------------------------------------------------------
func main() {
// DON'T TOUCH THIS:
lyric := strings.Fields(`all my troubles seemed so far away oh i believe in yesterday now it looks as though they are here to stay`)
// ADD YOUR CODE BELOW:
// ...
fmt.Printf("%s\n", lyric)
}

View File

@ -0,0 +1,79 @@
// 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"
"strings"
)
func main() {
// --- Correct Lyric ---
// yesterday all my troubles seemed so far away
// now it looks as though they are here to stay
// oh i believe in yesterday
lyric := strings.Fields(`all my troubles seemed so far away oh i believe in yesterday now it looks as though they are here to stay`)
// ------------------------------------------------------------------------
// #1: Prepend "yesterday" to `lyric`
// ------------------------------------------------------------------------
//
// --- BEFORE ---
// all my troubles seemed so far away oh i believe in yesterday
//
// --- AFTER ---
// yesterday all my troubles seemed so far away oh i believe in yesterday
//
// (warning: allocates a new backing array)
//
lyric = append([]string{"yesterday"}, lyric...)
// ------------------------------------------------------------------------
// #2: Put the words to the correct position in the `lyric` slice.
// ------------------------------------------------------------------------
//
// yesterday all my troubles seemed so far away oh i believe in yesterday
// | |
// v v
// index: 8 pos: 13
//
const N, M = 8, 13
// --- BEFORE ---
//
// yesterday all my troubles seemed so far away oh i believe in yesterday now it looks as though they are here to stay
//
// --- AFTER ---
// yesterday all my troubles seemed so far away oh i believe in yesterday now it looks as though they are here to stay oh i believe in yesterday
// ^
//
// |
// +--- duplicate
//
// (warning: allocates a new backing array)
lyric = append(lyric, lyric[N:M]...)
//
// --- BEFORE ---
// yesterday all my troubles seemed so far away oh i believe in yesterday now it looks as though they are here to stay oh i believe in yesterday
//
// --- AFTER ---
// yesterday all my troubles seemed so far away now it looks as though they are here to stay oh i believe in yesterday
//
// (does not allocate a new backing array because cap(lyric[:N]) > M)
//
lyric = append(lyric[:N], lyric[M:]...)
// ------------------------------------------------------------------------
// #3: Print
// ------------------------------------------------------------------------
fmt.Printf("%s\n", lyric)
}

View File

@ -52,3 +52,9 @@ These are warm-up exercises that will reinforce your knowledge of slices.
2. **[Sort the backing array](https://github.com/inancgumus/learngo/tree/master/16-slices/exercises/17-internals-backing-array-sort)**
3. **[Observe the memory allocations](https://github.com/inancgumus/learngo/tree/master/16-slices/exercises/18-internals-slice-header)**
4. **[Observe the length and capacity](https://github.com/inancgumus/learngo/tree/master/16-slices/exercises/19-observe-len-cap)**
5. **[Observe the capacity growth](https://github.com/inancgumus/learngo/tree/master/16-slices/exercises/20-observe-the-cap-growth)**
6. **[Correct the lyric](https://github.com/inancgumus/learngo/tree/master/16-slices/exercises/21-correct-the-lyric)**