Skip to content

Commit

Permalink
Update randint to have a more uniform distribution on range [0, limit]
Browse files Browse the repository at this point in the history
Signed-off-by: Siddharth Chandrasekaran <[email protected]>
  • Loading branch information
sidcha committed Sep 3, 2023
1 parent 2a1c3c8 commit 114df5b
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 5 deletions.
4 changes: 2 additions & 2 deletions include/utils/utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,11 @@
#define __weak __attribute__((weak))

/**
* @brief Return random number between `min` and `max` both inclusive.
* @brief Return random number between 0 and `limit` both inclusive.
*
* Note: the random number generator must be pre-seeded.
*/
int randint(int min, int max);
int randint(int limit);

/**
* @brief Rounds up 32-bit v to nearest power of 2. If v is already a power
Expand Down
10 changes: 8 additions & 2 deletions src/utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,15 @@

#include <utils/utils.h>

int randint(int min, int max)
int randint(int limit)
{
return (rand() % (max - min + 1)) + min;
int r;
int divisor = RAND_MAX / (limit + 1);

do {
r = rand() / divisor;
} while (r > limit);
return r;
}

uint32_t round_up_pow2(uint32_t v)
Expand Down
2 changes: 1 addition & 1 deletion tests/test-bus-server.c
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ int bus_write_check(int *fd)
char buf[128];
int i, write_fd;

write_fd = randint(0, NUM_CLIENTS - 1);
write_fd = randint(NUM_CLIENTS - 1);
ret = write(fd[write_fd], TEST_MSG, TEST_MSG_LEN);
if (ret != TEST_MSG_LEN) {
mod_printf("write %d failed!", write_fd);
Expand Down

0 comments on commit 114df5b

Please sign in to comment.