Skip to content

Commit 065d32e

Browse files
committed
Add Random function
1 parent 19037f3 commit 065d32e

File tree

3 files changed

+662
-160
lines changed

3 files changed

+662
-160
lines changed

fn.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@ package trit
22

33
import (
44
"context"
5+
"math/rand"
56
"reflect"
67
"runtime"
78
"sync"
9+
"time"
810
)
911

1012
var (
@@ -617,3 +619,48 @@ func IsConfidence[T Logicable](ts ...T) bool {
617619

618620
return true
619621
}
622+
623+
// Random returns a random Trit value.
624+
// The function can accept an optional argument that indicates the
625+
// percentage probability of the occurrence of the Unknown event.
626+
//
627+
// Example usage:
628+
//
629+
// a := trit.Random()
630+
// fmt.Println(a.String()) // Output: True, False or Unknown
631+
//
632+
// b := trit.Random(0)
633+
// fmt.Println(b.String()) // Output: True or False
634+
//
635+
// c := trit.Random(50)
636+
// fmt.Println(c.String()) // Output: With a probability of 50% is Unknown
637+
func Random(up ...uint8) Trit {
638+
// Determination of the probability of occurrence of the event Unknown.
639+
var p int
640+
641+
if len(up) == 0 {
642+
p = 33
643+
} else {
644+
for _, v := range up {
645+
p += int(v)
646+
}
647+
}
648+
649+
if p > 100 {
650+
p = 100
651+
}
652+
653+
// Generate random value.
654+
rand.Seed(time.Now().UnixNano())
655+
value := rand.Intn(100)
656+
657+
if value < p {
658+
return Unknown
659+
}
660+
661+
if value < (100-p)/2 {
662+
return True
663+
}
664+
665+
return False
666+
}

0 commit comments

Comments
 (0)