Random number range

• 09-02-2008
tzakieta
Random number range
Hi everyone,

I need an ideea for generating some ronadom characters to test the code i'm working on.
For now i want to generate just from A to Z so 65 to 90 in ASCII.
So my problem is reduced to generating numbers from 65 to 90.
Can you please give me a hint/ideea of how to restrict rand() between these limits?

Thank You.
• 09-02-2008
matsp
So what have you done so far?

To a moderator: Could we have the last two posts [and any subsequent ones following this] separated to a new thread, as I don't think it is particularly related to the original subject.

--
Mats
• 09-02-2008
tzakieta
:)
So far i've worked on the rest of the code where i'm "fighting" with malloc and some nasty pointers, but on the subject i've just searched somehow breiefly on some sites & docs i've bookmarked but nothing suggested any ideea.
Anyway i didn't asked for someone to solve my task or any code, but only for a hint, so it doesn't seem fair to take me for some guy too lazy to think/search.
I was just thinking about this while writing the main code. Anyway it's not necessary to use random chars, but because i've used random ints i just thought to do the char part in the same spirit. If the time spent on getting this doesn't pay for me, i'll just use a single char.
• 09-02-2008
matsp
It is easy to do, but I think you will learn more by doing it yourself.

Do you know how to make a random number that is limited to a certain range (e.g. 0..50)?
If you HAVE a random number that is limited to a certain range, how would you go about shifting it so that the range becomes X...X+50? And finally, what is the range you need to produce alphabetic numbers?

--
Mats
• 09-02-2008
tzakieta
Quote:

Originally Posted by matsp
Do you know how to make a random number that is limited to a certain range (e.g. 0..50)?

that's exactly my problem; range. i know about RAND_MAX but i don't see how it could help me.
I thought about making a function that checks if the random number is between 65-90 and then turn it into a char.

Quote:

Originally Posted by matsp
And finally, what is the range you need to produce alphabetic numbers?

I've already told you; from A to Z I need the range 65 to 90.
• 09-02-2008
matsp
Ok, so you are looking to limit the range of a number to 0..X, then you use % (X+1). Does that help?

--
Mats
• 09-02-2008
tzakieta
ok i got it.

Quote:

rand()%X = 0 to X-1;
so
MyX=65+rand()%26; // ((90-65)+1);
you lied, it's not that easy :D i have a headache now :).

• 09-02-2008
matsp
Yes, that's it. The generic form is:
Code:

int randrange(int min, max)
{
return rand() % (max - min + 1) + min;
}

--
Mats
• 09-02-2008
laserlight
I suggest that you read Prelude's article on using rand().
• 09-02-2008
master5001
Given why he is randomizing the data, it may not be necessary for him to make better intervals of values. But yes, its a good article that does present a lot of the issues with randomizing a program.