Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!uflorida!haven!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: How do I get random #s? Message-ID: <15979@mimsy.UUCP> Date: 16 Feb 89 16:15:17 GMT References: <19415@dhw68k.cts.com> <225800121@uxe.cso.uiuc.edu> <514@larry.UUCP> <1989Feb15.213335.18135@utzoo.uucp> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 42 In article <1989Feb15.213335.18135@utzoo.uucp> [love those message-IDs] henry@utzoo.uucp (Henry Spencer) writes: >However, as has been pointed out to me in private mail, the key issue when >you want multiple streams of random numbers is not being able to specify >a seed, but being able to save the state of rand() and restore it later. >*That*, the standard rand() can't do. Well, actually you can (as I pointed out in private mail, but I think not coherently). It is not suitable except as an exercise, but it goes like this: struct rand_stream { int rs_seed; unsigned long rs_calls; }; struct rand_stream *rs_start(int seed) { struct rand_stream *rs = malloc(sizeof(*rs)); if (rs == NULL) return (NULL); rs->rs_seed = seed; rs->rs_calls = 0; } int rs_rand(struct rand_stream *rs) { unsigned long l; srand(rs->rs_seed); for (l = 0; l < rs->rs_calls; l++) (void) rand(); rs->rs_calls++; return (rand()); } Incidentally, one of the big features of `object oriented' languages is that they encourage encapsulation of state into a data object, eliminating on a local level global (static) variables, obviating the need for the above sort of chicanery. -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris