From c7eafdbc5267da20cb3abb005dd442a6f2a9e66c Mon Sep 17 00:00:00 2001 From: "kayos@tcp.direct" Date: Sun, 11 Dec 2022 12:02:46 -0800 Subject: [PATCH] Fix[entropy]: fix `OneInA` function --- entropy/entropy.go | 3 +++ entropy/entropy_test.go | 16 ++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/entropy/entropy.go b/entropy/entropy.go index 0bd7315..5e5670b 100644 --- a/entropy/entropy.go +++ b/entropy/entropy.go @@ -73,6 +73,9 @@ func RNG(n int) int { // OneInA generates a random number with a maximum of 'million' (input int). // If the resulting random number is equal to 1, then the result is true. func OneInA(million int) bool { + if million == 1 { + return true + } return RNG(million) == 1 } diff --git a/entropy/entropy_test.go b/entropy/entropy_test.go index 8630dd6..0b59fc6 100644 --- a/entropy/entropy_test.go +++ b/entropy/entropy_test.go @@ -6,9 +6,13 @@ import ( "testing" ) +var dupCount = 0 + func check[T comparable](zero T, one T, t *testing.T) { if zero == one { + dupCount++ t.Errorf("hit a duplicate! %v == %v", zero, one) + t.Logf("duplicates so far: %d", dupCount) } } @@ -33,6 +37,18 @@ func Test_RNG(t *testing.T) { } } +func Test_OneInA(t *testing.T) { + for n := 0; n < 100; n++ { + yes := "" + if OneInA(1) { + yes = "hello" + } + if yes != "hello" { + t.Fatalf("OneInA failed to trigger when provided '1' as an argument") + } + } +} + func randStrChecks(zero, one string, t *testing.T, intendedLength int) { if len(zero) != len(one) { t.Fatalf("RandStr output length inconsistency, len(zero) is %d but wanted len(one) which is %d", len(zero), len(one))