File: sample.go

package info (click to toggle)
golang-github-montanaflynn-stats 0.7.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 460 kB
  • sloc: makefile: 27
file content (76 lines) | stat: -rw-r--r-- 1,427 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package stats

import (
	"math/rand"
	"sort"
)

// Sample returns sample from input with replacement or without
func Sample(input Float64Data, takenum int, replacement bool) ([]float64, error) {

	if input.Len() == 0 {
		return nil, EmptyInputErr
	}

	length := input.Len()
	if replacement {

		result := Float64Data{}
		rand.Seed(unixnano())

		// In every step, randomly take the num for
		for i := 0; i < takenum; i++ {
			idx := rand.Intn(length)
			result = append(result, input[idx])
		}

		return result, nil

	} else if !replacement && takenum <= length {

		rand.Seed(unixnano())

		// Get permutation of number of indexies
		perm := rand.Perm(length)
		result := Float64Data{}

		// Get element of input by permutated index
		for _, idx := range perm[0:takenum] {
			result = append(result, input[idx])
		}

		return result, nil

	}

	return nil, BoundsErr
}

// StableSample like stable sort, it returns samples from input while keeps the order of original data.
func StableSample(input Float64Data, takenum int) ([]float64, error) {
	if input.Len() == 0 {
		return nil, EmptyInputErr
	}

	length := input.Len()

	if takenum <= length {

		rand.Seed(unixnano())

		perm := rand.Perm(length)
		perm = perm[0:takenum]
		// Sort perm before applying
		sort.Ints(perm)
		result := Float64Data{}

		for _, idx := range perm {
			result = append(result, input[idx])
		}

		return result, nil

	}

	return nil, BoundsErr
}