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.
Related
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.
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();
}
}
This question already has answers here:
Why do I always get the same sequence of random numbers with rand()?
(12 answers)
If I don't specify srand(), what seed does rand() use?
(5 answers)
Closed 5 years ago.
Program uses rand() function to generate random index. But it always produces same string no matter what! Why won't this work?
void rand_string()
{
int a[10];
int i;
char b[] = "qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM";
printf("%d", sizeof(b) / sizeof(b[0]));
for(i = 0; i < 10; i++)
{
int gen_rand = rand() % 63;
a[i] = b[gen_rand];
}
for(i = 0; i < 10; i++)
printf("%c", a[i]);
}
Use srand function to seed the random generator
srand((unsigned)time(NULL));
Note that you only have to seed once in your program otherwise it will not work properly.
You could firstly define a random function specific to your needs, i.e. generating in specific range (the length of the current string), like so:
int random(int min, int max)
{
return min + (rand()) / (RAND_MAX / (max - min));
}
then in your string-random-generator function you could also add a random length to every string:
void rand_str()
{
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"; // define only on first call
// call srand() using #include <time.h> ; could be outside of function, i.e. in main()
int length = random(0, 10); // get random length in [0, 10] on each call
// use length and random(0, sizeof(alphanum) / sizeof(alphanum[0])) in for loop
// everything else is the same...
}
use the keyword static to indicate single1 definition of the array alphanum (think of it that it is like making it global) and call function srand() once, before the use of random().
Note: you should consider modifying your function to a single purpose, i.e. only generating a random string and returning (a pointer to) a string; and printing it in a separate function.
1. Only on the first call of rand_str().
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.
This question already has an answer here:
srand function is returning same values
(1 answer)
Closed 8 years ago.
I'm trying to make a function that generates random matrixes.
I'm not great at pointers but i really thought this should work.
Here's my function that I call twice from main, and that generates the same matrix in both cases...
int **generate_matrix(size_t m, size_t n){
int i1,i2;
int **ptr1=(int **)malloc(sizeof(int *)*m);
srand(time(0));
for(i1=0; i1<m; i1++){
ptr1[i1] = (int*)malloc(sizeof(int)*n);
for(i2=0; i2 < n; i2++){
ptr1[i1][i2]=rand()%10;
}
}
return ptr1;
}
In main i call them in a normal way:
int **matrix1,**matrix2;
matrix1=generate_matrix(3,3);
matrix2=generate_matrix(3,3);
(...)
//prints and stuff
free(matrix1);
free(matrix2);
You are seeding your rand with srand(time(0));. If your calculations are fast enough (i.e. the next second is not reached) time will return the same value twice due to its granularity of 1s.
You could check your results by seeding with definitely different numbers.