Skip to content

Commit c382f4d

Browse files
committed
rand: add missing rand.u16(), update doc comments, add test
1 parent 3a09142 commit c382f4d

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed

vlib/rand/rand.v

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,16 @@ pub fn seed(seed []u32) {
505505
default_rng.seed(seed)
506506
}
507507

508+
// u8 returns a uniformly distributed pseudorandom 8-bit unsigned positive `u8`.
509+
pub fn u8() u8 {
510+
return default_rng.u8()
511+
}
512+
513+
// u16 returns a uniformly distributed pseudorandom 16-bit unsigned positive `u16`.
514+
pub fn u16() u16 {
515+
return default_rng.u16()
516+
}
517+
508518
// u32 returns a uniformly distributed `u32` in range `[0, 2³²)`.
509519
pub fn u32() u32 {
510520
return default_rng.u32()
@@ -550,11 +560,6 @@ pub fn intn(max int) !int {
550560
return default_rng.intn(max)
551561
}
552562

553-
// byte returns a uniformly distributed pseudorandom 8-bit unsigned positive `byte`.
554-
pub fn u8() u8 {
555-
return default_rng.u8()
556-
}
557-
558563
// int_in_range returns a uniformly distributed pseudorandom 32-bit signed int in range `[min, max)`.
559564
// Both `min` and `max` can be negative, but we must have `min < max`.
560565
pub fn int_in_range(min int, max int) !int {

vlib/rand/random_numbers_test.v

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,31 @@ fn test_rand_u8() {
192192
assert all[0] != all[128]
193193
}
194194

195+
fn test_rand_u16() {
196+
mut all := []u16{}
197+
mut same_as_previous := 0
198+
mut previous := u16(0)
199+
for _ in 0 .. 65536 {
200+
x := rand.u16()
201+
assert x >= 0
202+
assert x <= 65535
203+
all << x
204+
if previous == x {
205+
same_as_previous++
206+
// dump(previous)
207+
// dump(x)
208+
}
209+
previous = x
210+
}
211+
assert same_as_previous < 1000
212+
all.sort(a < b)
213+
assert all[0] != all[65535]
214+
assert all[0] != all[32768]
215+
// dump( all[0] )
216+
// dump( all[65535] )
217+
// dump( all[32768] )
218+
}
219+
195220
const (
196221
string_count = 25
197222
)

0 commit comments

Comments
 (0)