using rand() in a function in c [duplicate] - c

This question already has answers here:
srand() — why call it only once?
(7 answers)
Closed 5 years ago.
I have made a function that creates a random number between 0 and 9 but when i call the function in main in a for loop with index i = 0 ; i < n ; i++ it prints 1 random number n types. but i want different values to be printed n times.
here is the code which i made :-
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void random_variable() {
int i;
srand(time(NULL));
i = rand()%10;
printf("%d ",i);
}
main() {
for(int j=0;j<10;j++) {
random_variable();
}
}
output is this :-
please click on the link to see the output :-
here instead of 8 ten times i needed 10 different values

srand() initializes the PRNG (pseudo random number generator) of your standard C library. A PRNG works by applying more-or-less complicated arithmetic operations to a value stored internally and returning part of the result as the next "random" number. srand() sets this internal state.
If you call srand() every time in your function, you won't get (sensible) random numbers because the internal state is reset every time. Call it once your program starts.

srand() seeds your random numbers. You want to do this once, not every time.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void random_variable() {
int i;
i = rand()%10;
printf("%d ",i);
}
main() {
srand(time(NULL));
for(int j=0;j<10;j++) {
random_variable();
}
}

Related

random shuffle in c [duplicate]

This question already has answers here:
srand() — why call it only once?
(7 answers)
Closed 2 years ago.
I'm trying to shuffle an array by following order:
user inputs the size of array
user inputs number of times to shuffle
shuffling function should run by selecting two random number(index) and switching the value of indices. For example, if I made my array arr[10], the fuction should pick two random numbers in range 0~9 and switch positions.
If the user typed 2 in step2, the function should repeat picking two random indices 2 times.
I tried, but something seems wrong(the two numbers are repeatedly identical). How can I get real random numbers?
void shuffle(int arr[], int size) {
srand(time(NULL));
int temp, rand1, rand2;
rand1 = rand() % size;
rand2 = rand() % size;
temp = arr[rand1];
arr[rand1] = arr[rand2];
arr[rand2] = temp;
}
void total_shuffle(int arr[], int size, int num) {
for (int i = 0; i < num; i++)
shuffle(arr, size);
}
You're seeding the (P)RNG multiple times, most likely with the same value as time() returns seconds, ergo the sequence produced by rand() will be the same, unless your program takes multiple seconds to run, or spans across a one-second boundary. Only call srand() once in your application.

Why does my srand(time(NULL)) function generate the same number every time in c? [duplicate]

This question already has answers here:
Random numbers in C
(10 answers)
How can I generate different random numbers for each player?
(3 answers)
Closed 4 years ago.
So I was creating a program that would call a function and return 0 or 1 (0 meaning tails and 1 meaning heads) and then use that to print the outcome of 100 flips.
It seemed simple enough thinking I could use srand(time(NULL)) to seed rand() with constantly varying seeds. Here was my first crack.
#include <stdio.h>
#include <stdlib.h>
int flip();
int main(void) {
int heads = 0;
int tails = 0;
for (short int count = 1; count <= 100; ++count) {
int number = flip();
if (number == 0) {
printf("%s", "Tails");
++tails;
}
else if (number == 1) {
printf_s("%s", "Heads");
++heads;
}
}//end for
printf_s("\n%d Tails\n", tails);
printf_s("%d Heads", heads);
}//end main
int flip(void) {
srand(time(NULL));
int number = (int)rand();
printf("%d", number%2);
return number%2;
}//end flip
I would run the program and my rand() value would always be a five digit integer repeated in each iteration of the for statement (i.e 15367, 15745, or 15943).
I messed around until I discovered changing srand(time(NULL)) to srand(time(NULL)*time(NULL)/rand()) did the trick.
My only thought is that the time between each for iteration is so small the the time(NULL) part of the srand() function doesn't change enough to feed a different seed value.
I also tried srand(time(NULL)/rand()), however, this produced the same result (52 heads 48 tails) every time I ran the program (20+times); however, the rand() values were all different from each other.
I do not know why these things happened, or why the final srand(time(NULL)*time(NULL)/rand()) function worked, and I would love it if someone could explain!
The reason is, that time(NULL) changes only once per second!
This means, that you seed the random number generator 100 times with the same seed.
A better way is to seed the RNG only once at start of the process (at the head of main(), then you should get different values.
If you start your program more often than once a second, you could also seed it with
srand(time(NULL)+getpid());
or similar.

How can i put different number in 2 array on C [duplicate]

This question already has answers here:
srand() — why call it only once?
(7 answers)
Closed 5 years ago.
I tried to put different random number element in each array.
However that 2 arrays got exactly same 10 random number.
What's wrong with me and how can I solve this?
#define MAX 100
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void number(int* array)
{
srand((long)time(NULL));
for (int i = 0; i < 20; i++)
array[i] = rand() % MAX + 1;
}
void printing(int* p_array)
{
for (int i = 0; i < 20; i++)
printf(" %d", p_array[i]);
puts("");
}
int main(void)
{
int score1[20];
int score2[20];
number(score1);
printing(score1);
number(score2);
printing(score2);
return 0;
}
srand((long)time(NULL));
When you are doing this, you are initializing srand with a seed based on the time the line has been called. The main point of a pseudo-number generator such as srand is that, whenever the seed is the same, the generator will always return the exact same serie of values, so a program using the generator with a specific seed can reproduce the exact same results several times.
The problem is that you initialize srand two times, and that the line is run two times at the exact same time (at least at the same second on such a short program), so the seed is the same. Your two arrays are, thus, strictly identical.
Call this line only once at the beginning of your main function, and you will use only one serie of numbers instead of two identical ones, leading to your two arrays having different values.
int main(void)
{
srand(time(NULL));
int score1[20];
int score2[20];
number(score1);
printing(score1);
number(score2);
printing(score2);
return 0;
}
Remove this statement from the number function
srand( (unsigned int)time(NULL));
and place it in main before the calls to number.
Otherwise the expression time(NULL) could yield the same value.
As 4386427 says, the problem is your call to srand(null). It resets the random number generator. If it didn't generate the same number series, then your number generator is broken. Remove it or call it with say the current time will fix the problem.

How to make random value function return different value each time [duplicate]

This question already has answers here:
Same random numbers every loop iteration
(4 answers)
Closed 8 years ago.
I've been trying to write a small C function for generating random values. The problem is that it returns same value each time the function is called in for loop. I understand the problem is that srand is seeded with NULL. What I want to know is how to correct it, so that on each iteration of for loop the function returns a different value. Here's the code:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int randInt(int,int);
void main(){
int min=100, max=200,i=0;
for(i;i<11;i++){ printf("%d \n",randInt(min,max)); }
}
int randInt(int a,int b){
srand(time(NULL));
int randValue;
randValue=1+(int)rand()%(b-a+1);
return randValue;
}
Please let me know if you have a solution or can post some reference to a solution. Thank you in advance !
Edit : Encountered Problem #2, after having replaced srand(time(NULL)) into main, every iteration now generates numbers bellow my range, i.e. originally i wanted numbers between 100 and 200, but it also included numbers between 0 and 100. This was solved with randValue=a+(int)rand()%(b-a+1); as suggested in the comments
Put srand(time(NULL)); in main just after the {
To generate random numbers in the range 100-200,instead of adding 1,add 100 or a to
randValue=(int)rand()%(b-a+1);
So that it looks like:
randValue=(int)rand()%(b-a+1)+100;
This will print random value each time between 100-200:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int randInt(int a,int b)
{
int randValue;
randValue = (rand() % (b-a+1)) + a;
return randValue;
}
int main(void) {
int r=0, i = 0;
srand(time(NULL));
do
{
r = randInt(100,200);
printf("%d\n",r);
i++;
}while(i < 11);
puts("Done!");
return 0;
}
I am using min and max insead of a and b. It is better for future readers of your code
You should use srand(time(NULL)) only once at initialization e.g in your main()
You probably wanted min + rand() % (max - min + 1) instead of rand()%(b-a+1)

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.

Resources