Generate random number in range [min,max] [duplicate] - c

This question already has answers here:
How to generate a random integer number from within a range
(11 answers)
Closed 7 years ago.
I am using C to generate a integer random number in range [min max]. I am using
int random_int(int min, int max)
{
return min + rand() % (max - min);
}
But I think above code is for range : [min, max), it is not for [min max]. Could you show to me a code to do my work. Best thanks

As you guessed, the code does indeed generate random numbers which do not include the max value. If you need to have the max value included in the range of random numbers generated, then the range becomes [min,max+1). So you could simply modify your code to:
int random_int(int min, int max)
{
return min + rand() % (max+1 - min);
}
P.S.: that is provided the quality of the original 'modulo' pseudo-random number generator you posted was not a concern (see this post for some more details with respect to what #undefinedbehaviour was referring to in comments).

Related

Generating unique random numbers except from a specific one in C [duplicate]

This question already has answers here:
Unique (non-repeating) random numbers in O(1)?
(22 answers)
Closed 9 years ago.
I was wondering, how can I generate unique random numbers except from a specific one. For example, if I want to generate numbers in range 1 to 10 except from 3, the output should be something like this:
7 6 1 2 4 9 5 8 10
Shuffle the numbers 1 - 10 and remove 3.
It doesn't matter if you remove the 3 before or after shuffling.
Alternatively, shuffle the numbers 1 - 9 and relabel 3 as 10...
For shuffling without bias you can use for example the Fisher-Yates algorithm. http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
Generate random number in the range 1..9 and add one if the number is greater than or equal to 3.
Generate a number. Check its value, if the number is 3 generate another one. If it isn't 3 then use it.
EDIT: Thinking before coffee is a terrible plan. If you want to get every number in the range in a random order then I agree with the others talking about shuffling lists. If however you want some random subset of the range I would store a list of forbidden values. Shuffling and only taking the first n numbers would also be suitable if the range isn't very large (e.g. not something like 0<x<INT_MAX).
Every time you generate a number check if the generated number is on the forbidden list and if it is, generate another number. Every time you generate a valid number you add it to the list to ensure generated numbers are unique. The list should also be initialised with your unwanted numbers (3 in the example given).
You may try like this:-
unsigned int
randomnumber(unsigned int min, unsigned int max)
{
double scaled = (double)rand()/RAND_MAX;
return (max - min +1)*scaled + min;
}
then later you can do this:-
x = randomnumber(1,10);
if (x==3)
{ x = x+1;}
or
if (x!=3)
{ printf("%d",x)}
This is my answer - returns random value in [min, max), except "except".
int myrand(int min, int max, int except) {
int rc;
do {
rc = min + rand() % (max - min);
} while(rc == except);
return rc;
}
This code will generate unique random numbers from minimum to maximum of a given range.
#include<stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int max_range, min_range, i = 0, rand_num;
srand((unsigned)time(NULL));
printf("Enter your maximum of range: ");
scanf("%d", &max_range);
printf("Enter your minimum of range: ");
scanf("%d", &min_range);
bool digit_seen[max_range + 1]; // VLAs For C99 only
for (int i = min_range; i <= max_range; i++)
digit_seen[i] = false;
for (;;)
{
rand_num = rand() % max_range + min_range;
if(rand_num !=3)
if(!digit_seen[rand_num])
{
printf("%d ", rand_num);
digit_seen[rand_num] = true;
i++;
}
if( i == (max_range - 1) )
exit(0);
}
return 0;
}

how to use rand() function with a range in C [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In C, how do I get a specific range of numbers from rand()?
Generate a random number within range?
I'm stuck on how to use the rand() function and include a range for that random number. I need a random number between 67.00 and 99.99 only to be printed.
This is what I have tried, but failed with...
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int x = rand();
if(x>=67.00)
if(x<=99.99)
printf("%d\n",x);
else
printf("not in range");
}
Instead of checking if the result is in the range, you can force the result to be in the range that you want:
int HIGH = 100;
int LOW = 67;
int rnd = LOW + (rand() % (HIGH-LOW));
The value of rnd is in the range between LOW and HIGH-1, inclusive.
If you do not want to force the number into range, change your condition to
if(x>=67.00 && x<=99.99)
Currently, the else belongs to the inner if, so the second printf does not happen when the number is less than 67.

Generate a Random Number between 1 and N-1 [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to generate a random number from within a range - C
How would you generate a random number between 1 and N-1 where N is a number the user punches in?
So far, my code is:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number = 0; //number variable
printf("This program will ask you for a number, an integer, and will print out a random number from the range of your number 1, to N-1.");//output that explains the program's purpose and use to the user.
//gets the input
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer, "%d", &number); //gets the input and stores it into variable number
return (0);
}
Try something like this:-
unsigned int
randomr(unsigned int min, unsigned int max)
{
double x= (double)rand()/RAND_MAX;
return (max - min +1)*x+ min;
}
Check out this link:- http://c-faq.com/lib/randrange.html
Here is the link to the referece for random.
http://www.cplusplus.com/reference/cstdlib/rand/
you can use
num= rand() % n + 1;
Depending on how "random" you want your numbers to be, you can use rand() function from the standard libc. This function will generate numbers between 0 and RAND_MAX. You can then get the result in the good range by using a modulo operation.
Note that this generator (a LCG) is neither suitable for cryptographic applications nor scientific applications.
If you want more suitable generators, have a look at generators such as Mersenne Twister (still not cryptosecure though).
You need to look at rand. Bit of maths and you have a solution.

How to assign a variable to rand() In C? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generate a random number within range?
I am trying to make it so when the code is executed, I can type the max number in
command prompt to redefine the max number and generate a new random number inbetween 0 and new Max number.
Did I do this correctly?
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main()
{
int randomnumber ;
int max;
srand( time(NULL) );
scanf("Enter total number of students %d",&max);
randomnumber=rand()% 30;
printf("This is your random number\n %d",randomnumber);
getchar();
return 0;
}
You've used the scanf to send a message to the user, but you need to use printf for that. Try:
printf("%s", "Enter total number of students: ");
scanf("%d",&max);
You can then change the %30 to %max to give the user a number between 0 and max - 1.
randomnumber=rand()% max;
As commenters have said, using modulo to reduce the range of rand() will not give you a good random distribution. Also, be sure to check that max is greater than 0, otherwise you will get an error.
If you're wondering why you're getting a large number in max at the moment, it is because you're not initializing max explicitly. With C and C++ this means that there can be junk data in there. It is not like Java or C# where an int is automatically initialized to 0.

Generate a random number within range? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Generating Random Numbers in Objective-C
How do I generate a random number which is within a range?
This is actually a bit harder to get really correct than most people realize:
int rand_lim(int limit) {
/* return a random number between 0 and limit inclusive.
*/
int divisor = RAND_MAX/(limit+1);
int retval;
do {
retval = rand() / divisor;
} while (retval > limit);
return retval;
}
Attempts that just use % (or, equivalently, /) to get the numbers in a range almost inevitably introduce skew (i.e., some numbers will be generated more often than others).
As to why using % produces skewed results: unless the range you want is a divisor of RAND_MAX, skew is inevitable. If you start with small numbers, it's pretty easy to see why. Consider taking 10 pieces of candy (that we'll assume you can't cut, break, etc. into smaller pieces) and trying to divide it evenly between three children. Clearly it can't be done--if you hand out all the candy, the closest you can get is for two kids to get three pieces of candy, and one of them getting four.
There's only one way for all the kids to get the same number of pieces of candy: make sure you don't hand out the last piece of candy at all.
To relate this to the code above, let's start by numbering the candies from 1 to 10 and the kids from 1 to 3. The initial division says since there are three kids, our divisor is three. We then pull a random candy from the bucket, look at its number and divide by three and hand it to that kid -- but if the result is greater than 3 (i.e. we've picked out candy number 10) we just don't hand it out at all -- we discard it and pick out another candy.
Of course, if you're using a modern implementation of C++ (i.e., one that supports C++11 or newer), you should usually use one the distribution classes from the standard library. The code above corresponds most closely with std::uniform_int_distribution, but the standard library also includes uniform_real_distribution as well as classes for a number of non-uniform distributions (Bernoulli, Poisson, normal, maybe a couple others I don't remember at the moment).
int rand_range(int min_n, int max_n)
{
return rand() % (max_n - min_n + 1) + min_n;
}
For fractions:
double rand_range(double min_n, double max_n)
{
return (double)rand()/RAND_MAX * (max_n - min_n) + min_n;
}
For an integer value in the range [min,max):
double scale = (double) (max - min) / RAND_MAX;
int val = min + floor(rand() * scale)
I wrote this specifically in Obj-C for an iPhone project:
- (int) intInRangeMinimum:(int)min andMaximum:(int)max {
if (min > max) { return -1; }
int adjustedMax = (max + 1) - min; // arc4random returns within the set {min, (max - 1)}
int random = arc4random() % adjustedMax;
int result = random + min;
return result;
}
To use:
int newNumber = [aClass intInRangeMinimum:1 andMaximum:100];
Add salt to taste
+(NSInteger)randomNumberWithMin:(NSInteger)min WithMax:(NSInteger)max {
if (min>max) {
int tempMax=max;
max=min;
min=tempMax;
}
int randomy=arc4random() % (max-min+1);
randomy=randomy+min;
return randomy;
}
I use this method in a random number related class I made. Works well for my non-demanding needs, but may well be biased in some way.

Resources