Slices

Shuffle the Slice

  • This example is for int
    • Requires function for each type and interface
package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    s := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    shuffle(s)
    fmt.Println(s)  // [10 2 6 7 8 9 4 1 5 3]
}

func shuffle(s []int) {
    source := rand.NewSource(time.Now().UnixNano())
    r := rand.New(source)

    for i := range s {
        newPosition := r.Intn(len(s) - 1)
        s[i], s[newPosition] = s[newPosition], s[i]
    }
}

Compare 2 Slices

  • This example is for int
    • Requires function for each type and interface
package main

import "fmt"

func main() {
    s1 := []int{1, 2, 3, 4}
    s2 := []int{2, 4, 5, 6}

    fmt.Println(testEq(s1, s2)) // false
}

func testEq(a, b []int) bool {

    if a == nil && b == nil {
        return true
    }

    if a == nil || b == nil {
        return false
    }

    if len(a) != len(b) {
        return false
    }

    for i := range a {
        if a[i] != b[i] {
            return false
        }
    }

    return true
}

Get Max number from a slice of integers

package main

import "fmt"

func main() {
    s1 := []int{1, 2, 3, 4}

    fmt.Println(max(s1)) // 4
}

func max(arr []int) int {
    r := arr[0]

    for _, value := range arr {
        if r < value {
            r = value
        }
    }
    return r
}

Filter function

package main

import "fmt"

func filter(numbers []int, callback func(int) bool) []int {
    var xs []int
    for _, n := range numbers {
        if callback(n) {
            xs = append(xs, n)
        }
    }
    return xs
}

func main() {
    xs := filter([]int{1, 2, 3, 4}, func(n int) bool {
        return n > 1
    })
    fmt.Println(xs) // [2 3 4]
}

results matching ""

    No results matching ""