Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

How do I make this faster?

Name: Anonymous 2019-09-10 17:01

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int myrand(int min, int max) {
int new_value;
static int previous_value;

if(min > max) return 1;

do {
srand(time(NULL));
new_value = rand() % (max - min);
} while(new_value == previous_value);

previous_value = new_value;
return new_value;
}

int main() {
for(register char c = 0; c < 5; c++) {
printf("%c\t", myrand(33, 126));
}

putchar('\n');
return 0;
}

Name: Anonymous 2019-09-11 7:00

what are you even trying to achieve? I guess it is to have a RNG which returns numbers between between min and max. the way to do it correctly would be new_value = min + rand() % (max-min), as the current implementation doesn't do this correctly. the loop is entirely unnecessary - there is no need to ensure that new value is different than previous, as random numbers can repeat. I guess your're are problem was that you were getting the same number repeated all the time, but this is because your're are using srand() wrong. it re-seeds the global RNG, so calling it should not be the responsibility of myrand() but of the calling program. also, unrelated to speed: returning 1 is weird here because 1 is a valid return value of an RNG, I'd rather use errno to indicate wrong arguments.
a rough solution would look like this (warning: I did not compile it):

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int myrand(int min, int max) {
if(min > max){
errno = EINVAL;
return 0;
}
return min + (rand()%(max-min));
}

int main() {
srand(time(NULL));
for(register char c = 0; c < 5; c++) {
printf("%c\t", myrand(33, 126));
}

putchar('\n');
return 0;
}


if you really need to seed the global RNG inside myrand() (and you really shouldn't), you can do something like this:

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int myrand(int min, int max) {
static short seeded = 0; //assuming your're are using a standard from before bool type
if(!seeded){
srand(time(NULL));
seeded = 1;
}
if(min > max){
errno = EINVAL;
return 0;
}
return min + (rand()%(max-min));
}

int main() {
for(register char c = 0; c < 5; c++) {
printf("%c\t", myrand(33, 126));
}

putchar('\n');
return 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List