Go语言学习

2018-05-10  本文已影响0人  HeartLeo

Go 是一个开源的编程语言,它能让构造简单、可靠且高效的软件变得容易


Go 语言特色:

  • 简洁、快速、安全
  • 并行、有趣、开源
  • 内存管理、快速编译

  1. 支持如下两种方式来加载自定义包:
//根据相对路径标识导入自定义包
import (
    "./test"
)
//导入src下的自定义包
import (
    "Test/test"
)

  1. 特殊的import方式:
import (
    . "Test/test"
)
import (
    T "Test/test"
)
import (
    _ "Test/test"
)

  1. 包的导入流程:

4.蓄水池抽样法 - Reservoir Sampling

//ReservoirSampling - A function to randomly select k items from stream[0..n-1]
func ReservoirSampling(stream []int, n int, k int) {
    //reservoir is the output slice
    reservoir := make([]int, k, k)
    // Initialize it with first k elements from stream
    for i := 0; i < k; i++ {
        reservoir[i] = stream[i]
    }
    // Use a different seed value
    rand.Seed(time.Now().Unix())
    // Iterate from the (k+1)th element to nth element
    for j := k; j < n; j++ {
        // Pick a random index from 0 to j
        r := rand.Intn(j + 1)
        // If the randomly picked index is smaller than k, replace the element present at the index with new element from stream
        if r < k {
            reservoir[r] = stream[j]
        }
    }
    //Print the output slice
    fmt.Println(reservoir)
}

上一篇下一篇

猜你喜欢

热点阅读