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

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.

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.

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.

Takes 2 different random number in C language [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
calling rand() returning non-random results
In my workshop I need to takes 2 different random numbers but I get 2 same random number.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int random1_6(){
int k;
srand(time(0));
k=((rand()%6)+1);
return k;
}
int main(void){
int a,b;
a=random1_6();
printf("%d.\n",a);
b=random1_6();
printf("%d.\n",b);
return 0;
}
How to get 2 different random number?
A non-cryptographic random number generator (RNG) is not truely random but it generates random-like numbers based on a seed.
What you do is initializing the RNG with the same seed two times, so you get the same results. Seed the RNG just once, e.g. at program start, and you will get random-like different results.
Edit: a code like follows should work:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int random1_6(){
return ((rand() % 6) + 1);
}
int main(void){
int a,b;
srand(time(NULL));
a = random1_6();
printf("%d.\n",a);
b=random1_6();
printf("%d.\n",b);
return 0;
}
Don't do srand(time(0)); on every call. Only call it once.
You must initialize the random number generator seed with srand() only once : upon each call you are re-initializing the RNG with the same seed since is it most likely that the two subsequent calls to time(0) will return the same timestamp (seconds-level precision), hence rand() will return the same number twice.
If you call srand() only once at the beginning of your program (in the main() entry-point), then every call to rand() will return a different number.
You always initialize the random number generator with the same seed, so you'll get the same random sequence, it is pseudo random anyway. Typically you will only want to call srand once in the beginning to initialize the generator.
Also, you only have 6 different possible outcomes, so it is perfectly legitimate to get same number twice, there is 1/6 chance for that.

Why isn't this number random?

For the following piece of code:
#include<stdlib.h>
#include<stdio.h>
int main()
{
int x;
x = rand()%100;
printf("The Random Number is: %i", x);
return 0;
}
It always seems to print the random number as 83. Why is this?
Most random number generators are repeatable. You need to seed the generator before using it which you typically do using the system time.
#include <time.h>
srand(time(NULL));
Obligatory XKCD reference:
As people have said, you need to seed the pseudo random number generator properly.
The trouble is, it still only generates pseudo random numbers. Most "true" random number generators require access to some physical phenomenon that is random in nature (for example, clock skews or temperature fluctuations).
Otherwise, the XKCD reference is not too far from the truth. Nor is Dilbert.
Because the pseudo-random number generator used by rand is always initialized with the same seed.
In order to initialize it with a different seed, you can use the srand function, and initialize it as, say, srand(time(NULL)).
Because 83 is a random number, isn't it ?
More seriously, it is useful to have programs providing a repeatable behavior so by default, rand always returns the same sequence of numbers if you don't change the seed.
Seed the random number generator by including <time.h> and calling srand(time(0)); (edited thanks to my commenters)
You can not generate a random number which is truly random until and unless your random number generator has access to a truly random physical phenomenon as quoted earlier by peter. But for a general use you can use C's standard library functions for generating random numbers. Here is a sample code for generating random number between two limits(max and min):
#include<stdio.h>
#include<stdlib.h>
#define MIN 1
#define MAX 5
#define QUANTITY 5
int main()
{
int i;
//stores the time in seconds
time_t seconds;
//getting the system time
time(&seconds);
//initializing the random generator with system time
//as the seed value
srand((long)seconds);
for(i = 0; i < QUANTITY; i++)
{
printf("%f\t",((float)rand())/RAND_MAX*(MAX-MIN)+MIN);
}
printf("\n");
return 0;
}

Resources