Random Number...

Post Reply
Sylus101
Posts: 179
Joined: Wed Dec 24, 2008 5:08 am

Random Number...

Post by Sylus101 » Tue May 12, 2009 11:38 pm

I've found (though I wouldn't be adverse to getting another suggestion) about the proper way to generate a random number (with a max value), but to seed the random number generator I'd like to use the current DS Clock time. I can't seem to find any macro or define for it... what am I missing?
-Sylus "Not Stylus..." McFrederickson

Come visit my web site.

WinterMute
Site Admin
Posts: 2060
Joined: Tue Aug 09, 2005 3:21 am
Location: UK
Contact:

Re: Random Number...

Post by WinterMute » Wed May 13, 2009 2:17 am

Code: Select all

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

int main(int argc, char **argv) {
  consoleDemoInit();
  srand(time(NULL));
  printf("random number is %d\n", rand());
  while(1) swiWaitForVBlank();
}
Help keep devkitPro toolchains free, Donate today

Personal Blog

Sylus101
Posts: 179
Joined: Wed Dec 24, 2008 5:08 am

Re: Random Number...

Post by Sylus101 » Wed May 13, 2009 3:42 am

Thanks, that works, lol.

Another quick question... should you only have to call srand() once? What I mean is, afterwards will rand() generate a number seeded by the time at that moment or at the moment srand() was called.
-Sylus "Not Stylus..." McFrederickson

Come visit my web site.

User avatar
vuurrobin
Posts: 219
Joined: Fri Jul 11, 2008 8:49 pm
Location: The Netherlands
Contact:

Re: Random Number...

Post by vuurrobin » Wed May 13, 2009 12:03 pm

time is just a function that a number. so srand will always use the time it was given when you called time().
however, you only have to call srand() once. when you call rand(), it will change the seed for you, so calling rand() twice should give you 2 different numbers.

Jell
Posts: 2
Joined: Wed May 27, 2009 11:31 am

Re: Random Number...

Post by Jell » Wed May 27, 2009 11:43 am

I ran through this problem lately, actually srand(time(NULL)) did not randomize my rand() calls.

My guess WAS that the function time() returns a pointer, therefore your seed will always be the same (making the whole process useless).

[Edit:] But obviously I was guessing wrong!
Last edited by Jell on Wed May 27, 2009 2:34 pm, edited 1 time in total.

WinterMute
Site Admin
Posts: 2060
Joined: Tue Aug 09, 2005 3:21 am
Location: UK
Contact:

Re: Random Number...

Post by WinterMute » Wed May 27, 2009 2:00 pm

Actually, srand(time(NULL)) will work fine, just not on most emulators.
Help keep devkitPro toolchains free, Donate today

Personal Blog

Jell
Posts: 2
Joined: Wed May 27, 2009 11:31 am

Re: Random Number...

Post by Jell » Wed May 27, 2009 2:24 pm

Oups that's true! Sorry for the wrong advice...

Post Reply

Who is online

Users browsing this forum: No registered users and 2 guests