go-chart/seq/random.go

89 lines
1.7 KiB
Go
Raw Normal View History

2017-05-12 17:17:43 -04:00
package seq
2017-04-30 00:12:39 -04:00
2017-04-30 01:44:17 -04:00
import (
"math"
"math/rand"
2017-04-30 03:39:38 -04:00
"time"
2017-04-30 01:44:17 -04:00
)
2017-04-30 00:12:39 -04:00
2017-04-30 03:39:38 -04:00
// RandomValues returns an array of random values.
func RandomValues(count int) []float64 {
return Seq{NewRandom().WithLen(count)}.Array()
}
// RandomValuesWithAverage returns an array of random values with a given average.
2017-05-12 20:06:45 -04:00
func RandomValuesWithMax(count int, max float64) []float64 {
return Seq{NewRandom().WithMax(max).WithLen(count)}.Array()
2017-04-30 03:39:38 -04:00
}
2017-05-12 17:17:43 -04:00
// NewRandom creates a new random seq.
2017-04-30 03:39:38 -04:00
func NewRandom() *Random {
return &Random{
rnd: rand.New(rand.NewSource(time.Now().Unix())),
}
}
2017-05-12 17:17:43 -04:00
// Random is a random number seq generator.
2017-04-30 00:12:39 -04:00
type Random struct {
2017-05-12 20:06:45 -04:00
rnd *rand.Rand
max *float64
min *float64
len *int
2017-04-30 00:12:39 -04:00
}
2017-04-30 01:44:17 -04:00
// Len returns the number of elements that will be generated.
2017-04-30 00:12:39 -04:00
func (r *Random) Len() int {
2017-04-30 01:44:17 -04:00
if r.len != nil {
return *r.len
}
return math.MaxInt32
2017-04-30 00:12:39 -04:00
}
2017-04-30 01:44:17 -04:00
// GetValue returns the value.
2017-04-30 00:12:39 -04:00
func (r *Random) GetValue(_ int) float64 {
2017-05-12 20:06:45 -04:00
if r.min != nil && r.max != nil {
var delta float64
if *r.max > *r.min {
delta = *r.max - *r.min
} else {
delta = *r.min - *r.max
}
return *r.min + (r.rnd.Float64() * delta)
} else if r.max != nil {
return r.rnd.Float64() * *r.max
} else if r.min != nil {
return *r.min + (r.rnd.Float64())
2017-04-30 00:12:39 -04:00
}
return r.rnd.Float64()
}
2017-04-30 01:44:17 -04:00
// WithLen sets a maximum len
func (r *Random) WithLen(length int) *Random {
r.len = &length
return r
}
2017-05-12 20:06:45 -04:00
// Min returns the minimum value.
func (r Random) Min() *float64 {
return r.min
2017-05-12 17:17:43 -04:00
}
2017-05-12 20:06:45 -04:00
// WithMin sets the scale and returns the Random.
func (r *Random) WithMin(min float64) *Random {
r.min = &min
2017-04-30 01:44:17 -04:00
return r
}
2017-05-12 20:06:45 -04:00
// Max returns the maximum value.
func (r Random) Max() *float64 {
return r.max
2017-05-12 17:17:43 -04:00
}
2017-05-12 20:06:45 -04:00
// WithMax sets the average and returns the Random.
func (r *Random) WithMax(max float64) *Random {
r.max = &max
2017-04-30 01:44:17 -04:00
return r
}