Ask your own question, for FREE!
Computer Science 16 Online
OpenStudy (anonymous):

I have a strange problem involving the following macro: \[#define shuffle(sequence, len) do \ { \ fprintf(stderr, "%s\n", TIME_LINE_FILE); \ unsigned int k; \ unsigned int count = (len); \ while (count > 1) \ { \ k = rand_range(count); \ --count; \ swap((sequence)[count], (sequence)[k]); \ } \ } while (0) \] When you pass a number larger than 32767 (what's special about this number is that it is equal to 2^16 - 1), it breaks. What is wrong with it?

OpenStudy (anonymous):

when you pass a number larger than 32767 as len, it breaks*

OpenStudy (anonymous):

I've narrowed the problem to this function: \[# int random_in_range(unsigned int min, unsigned int max) { int base_random, range, remainder, bucket; do { do { base_random = rand(); } while (RAND_MAX == base_random); range = max - min; remainder = RAND_MAX % range; bucket = RAND_MAX / range; } while (base_random >= (RAND_MAX - remainder)); return min + (base_random / bucket); }\] with min equal to 0, and max equal to a number larger than 32767, this function just breaks.

OpenStudy (anonymous):

ahh... RAND_MAX happens to equal to 32767

OpenStudy (anonymous):

well... now I have a new question.... how do i get a better rand() function in C?

OpenStudy (anonymous):

because the default rand() stuff in C just sucks :(

OpenStudy (anonymous):

be more specific; what don't you like about the default rand() (and perhaps ask a separate question)?

OpenStudy (anonymous):

it only goes from 0 to 2^15 - 1

OpenStudy (anonymous):

RAND_MAX is not fixed. In the GNU library it's 2^31-1; not sure what you're using. You just need to scale it properly. If you need a higher resolution you can always just call it again. E. g. int my_rand(){ return rand()*32768+rand(); }

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!