generate random a number number between two limits - c

Is there a way to generate a number number between two limits without using the sran and rand function
What it is that i have a while (1) (super loop) which calls a function every 10 ms seconds. in the function a for loop is used to create a delay, but, everytime the function is access the delay should be different but between two limts, 8 and 2 ms, for(x=0;x<random_number;x++)

Try bellow hope this will answer your question.
#include<stdio.h>
#include <stdlib.h>
int main()
{
int iMaxRand =100,ii=0 ;
while( ii < 100)
{
printf("Random Number is:%d\n", rand() % iMaxRand);
ii++;
}
printf("\n");
}

Related

"Big Pig" dice game code goes in infinite loop :C

Hello I'm new to c and i'm currently learning with my university curriculum so i need to abide by these rules: We can't use arrays or global variables.
So i've been trying to make a dice game named "big pig". I'm right now creating the function the computer is going to use to play the game called "play_computer()". There is also a function called "computer_strategy_decider()".Computer_strategy_decider() is supposed to pick from yes or no. I just made a rand function that calls either 1 or 2 to make that work. Play_computer() let's you pick two dices and from there it needs to calculate the score. If you pick only one one, then your score doesn't increase and your game is terminated. If you et two ones you get 25 added. If you get any other double value for example a , is added such as (a+a)*2 or 4*a. And lastly if you get two random numbers the computer gets to decide if it wants to continue. That's where the computer_strategy_decider() comes in..
The problem comes with the play_computer() function. Everything seems to be working well when the computer rolls two different values and doesn't continue. It terminates ok. But if it wants to continue it goes in an infinite loop. The infinite loop also has the same dice values.
The same loop happens when doubles are rolled. Something in my code doesn't loop properly. I don't know whether it is something to do with rand() or not. I don't think it's rand() since i use rand() on computer_strategy_decider(). My theory is it's hopefully something small i have missed.
My code was working an hour ago before i added some changes so that's why im frustrated haha.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
int computer_strategy_decider(){
int deci;
srand(time(NULL));
deci=1+ (int) rand() % 2;
return deci;}
int play_computer(round_number,strategy){
int roll_1,roll_2,cntrl_var=0,score_comp=0;
char answ;
printf("\nRound %d-- My Turn:",round_number);printf("\n---------------------------------");
while(cntrl_var==0){
srand(time(NULL));
roll_1 = 1 + (int) rand() % 6;
roll_2 = 1 + (int) rand() % 6;
printf("\nI got --> [Dice 1]: %d [Dice 2]: %d",roll_1,roll_2);
if(roll_1==roll_2 && roll_1!=1){
score_comp=score_comp+roll_1*4;
printf("\nScore: %d",score_comp);printf("\nDoubles! Roll again!");}
else if(roll_1==1 && roll_2==1){
score_comp=score_comp+25;
printf("\nScore: %d",score_comp);printf("\nDoubles! Roll again!");}
else if(roll_1==1 || roll_2==1){
cntrl_var=1;
printf("\nYou got a single one! End of your turn!");}
else{
score_comp=score_comp+roll_1+roll_2;
printf("\nScore: %d",score_comp);
while(cntrl_var==0){
printf("\nDo you want to continue (Y/N)?");
if (strategy==1){
printf("Y");
break;}
else if (strategy==2){
printf("N");
break;}}
if (strategy==1)
cntrl_var=0;
else if (strategy==2)
cntrl_var=1;
else
cntrl_var=0;}}
printf("\nMy Score: %d",score_comp);
return score_comp;}
int main(){
int round_no=1,deci;
deci=computer_strategy_decider();
play_computer(round_no,deci);
}
I put the srand in the while loop and that caused the srand to be called multiple times. So i put the srand above the loop. That fixed it!

Program doesn't work when rrun normally, but with debug step by step the result is right

In the code below, which I wrote on visual studio 2013, I pressed Ctrl+F5 but don't print the right result, I debug it step by step the results is right.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdint.h>
int randfoo(void)
{
time_t ts;
int a[10];
unsigned int randdata = time(&ts);
srand(randdata);
return (rand() % 100);
}
int randNumber(int firstNum, int lastNumber, int result[][6])
{
int ret_val = -1;
int value1;
if ((firstNum > 0) && (firstNum < 5))
{
if ((lastNumber>0) && (lastNumber < 7))
{
for (int i = 0; i < firstNum; i++)
{
for (int j = 0; j < lastNumber; j++)
{
value1 = randfoo();
result[i][j] = value1;
printf("a[%d][%d]=%d\n", i, j, result[i][j]);
}
}
ret_val = 0;
}
else
{
ret_val = -1;
}
}
else
{
ret_val = -1;
}
return ret_val;
}
void main()
{
int buff[4][6];
randNumber(4, 6, buff);
system("pause");
}
the first function randfoo just to generate a rand number.
the second function randNumber in order to put the rand number into the result[4][6],and print the results.
You used srand(randdata); on each call to randfoo(). srand() is used to seed the PRNG for rand(). You don't seed it every time.
Just use srand(randdata) once in main() and rand() % 100 directly in all the assignments.
You can get rid of the whole randfoo() function, IMHO.
Random wont be random enough if you access it again and again repeatedly in the time of CPU cycles. To read more about rand please read this page.
The period of rand is implementation defined, but typically falls
around 2^32-1. Compare this with the Mersenne Twister algorithm, which
is 2^19937-1. You typically want the period of a random number
generator to exceed the amount of numbers expected to be generated,
because that's the point where the sequence repeats.
From another answer in SO (source link):
Don't call srand before every call to rand. Call it once when your
program starts.
You may want to look at this SO question.
It may be useful to explain the reason it "works" when you debug it and "doesn't work" when you run it.
When you run it normally it executes in much less time than 1 second. Thus, the time() function always returns the same time (unless you get very lucky and run it exactly on a second boundary) and thus you call srand() with the same value and so rand() returns the same value for each call to randfoo().
When you debug it, however, it probably takes a few seconds between calls to randfoo() thus you get different time() values, which seeds the pseudo-random generator with different values, and thus different rand() values.
A great example of a Heisenbug, a bug that disappears when you try to find it. The solution, as the other answers say, is to simply call srand() once at the program start.

How do I create a "twirly" in a C program task?

Hey guys I have created a program in C that tests all numbers between 1 and 10000 to check if they are perfect using a function that determines whether a number is perfect. Once it finds these it prints them to the user, they are 6, 28, 496 and 8128. After this the program then prints out all the factors of each perfect number to the user. This is all fine. Here is my problem.
The final part of my task asks me to:
"Use a "twirly" to indicate that your program is happily working away. A "twirly" is the following characters printed over the top of each other in the following order: '|' '/' '-' '\'. This has the effect of producing a spinning wheel - ie a "twirly". Hint: to do this you can use \r (instead of \n) in printf to give a carriage return only (instead of a carriage return linefeed). (Note: this may not work on some systems - you do not have to do it this way.)"
I have no idea what a twirly is or how to implement one. My tutor said it has something to do with the sleep and delay functions which I also don't know how to use. Can anyone help me with this last stage, it sucks that all my coding is complete but I can't get this "twirly" thing to work.
if you want to simultaneously perform the task of
Testing the numbers and
Display the twirly on screen
while the process goes on then you better look into using threads. using POSIX threads you can initiate the task on a thread and the other thread will display the twirly to the user on terminal.
#include<stdlib.h>
#include<pthread.h>
int Test();
void Display();
int main(){
// create threads each for both tasks test and Display
//call threads
//wait for Test thread to finish
//terminate display thread after Test thread completes
//exit code
}
Refer chapter 12 for threads
beginning linux programming ebook
Given the program upon which the user is "waiting", I believe the problem as stated and the solutions using sleep() or threads are misguided.
To produce all the perfect numbers below 10,000 using C on a modern personal computer takes about 1/10 of a second. So any device to show the computer is "happily working away" would either never be seen or would significanly intefere with the time it takes to get the job done.
But let's make a working twirly for perfect number search anyway. I've left off printing the factors to keep this simple. Since 10,000 is too low to see the twirly in action, I've upped the limit to 100,000:
#include <stdio.h>
#include <string.h>
int main()
{
const char *twirly = "|/-\\";
for (unsigned x = 1; x <= 100000; x++)
{
unsigned sum = 0;
for (unsigned i = 1; i <= x / 2; i++)
{
if (x % i == 0)
{
sum += i;
}
}
if (sum == x)
{
printf("%d\n", x);
}
printf("%c\r", twirly[x / 2500 % strlen(twirly)]);
}
return 0;
}
No need for sleep() or threads, just key it into the complexity of the problem itself and have it update at reasonable intervals.
Now here's the catch, although the above works, the user will never see a fifth perfect number pop out with a 100,000 limit and even with a 100,000,000 limit, which should produce one more, they'll likely give up as this is a bad (slow) algorithm for finding them. But they'll have a twirly to watch.
i as integer
loop i: 1 to 10000
loop j: 1 to i/2
sum as integer
set sum = 0
if i%j == 0
sum+=j
return sum==i
if i%100 == 0
str as character pointer
set *str = "|/-\\"
set length = 4
print str[p] using "%c\r" as format specifier
Increment p and assign its modulo by len to p

time dependent uniformly distributed random number

I need a uniformly distributed random number generator...
Here is what I've tried its output is a constant number no matter how many time i run the .exe
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int randr( int min, int max);
int main()
{
srand(time(NULL));
int rr=randr(0,10);
printf("rr=%d\n",rr)
return 0;
}
int randr( int min, int max)
{
double scaled = (double)rand()/RAND_MAX;
return (max - min +1)*scaled + min;
}
Thanks in advance.
The problem with your code is that the time function doesn't use milliseconds, so each call to your function set the same seed and generate the same first number (assuming it's called at the same time, i.e. the same second).
One way to avoid this is to give a seed only once in your program (srand must be called only once), you can verify that by trying this code :
int main()
{
int a = 0;
srand(time(NULL));
for (int i=0;i<10000;i++){
int rr=randr(0,10);
a+=rr;
printf("rr=%d\n",rr);
}
printf("mean : %d\n", a/10000); // to quickly check the uniformity
return 0;
}
Another way is to use a function that can give you a different seed at each call (time based on milliseconds for example). A possible implementation on a POSIX system :
struct timespec tmp;
clock_gettime(CLOCK_MONOTONIC,&tmp);
srand(tmp.tv_nsec);
This will be based on nanoseconds (as suggested by R..), to compile you'll probably need to link with librt (-lrt on gcc).

Really weird, debug of the program works OK but when i run it i get a weird result

i'm trying to create a 'game' in C programming which throws 2 dices for the user, throws 2 dices for the PC, and whoever gets the bigger sum wins,
when i debug it in visual studio i see good results both in the variable values and the console window, but when i run it without debugging the user and the PC both always get the same value for their dices (user gets 2 and 2, and PC gets 2 and 2, for example).
Can anyone solve it? i looked at it for the last 3 hours and i just can't find what's the problem.
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int throwDice();
int diceSum();
int main()
{
int res1;
res1=diceSum();
if(res1==0)
printf("It is a tie!\n");
if(res1==1)
printf("You Won!\n");
if(res1==-1)
printf("You Lost\n");
}
int throwDice()
{
int i;
srand((unsigned)time(NULL));
i = (rand()%(6-1)) + 1;
return i;
}
int diceSum()
{
int j,a=0,b,c=0,d=0;
int array[4];
for(j=1;j<=2;j++)
{
array[c]=throwDice();
a=a+array[c];
c++;
}
for(b=1;b<=2;b++)
{
array[c]=throwDice();
d=d+array[c];
c++;
}
printf("You got %d and %d.\nYour opponent got %d and %d.\n",array[0],array[1],array[2],array[3]);
if(a==d)
return 0;
if(a>d)
return 1;
else
return -1;
}
Everytime you call throwDice, you are re-initializing your random number generator with the current time.
The accuracy of time is only 1-second, so in a single run of this program, the time doesn't change, so you get the same results.
You are supposed to call srand ONLY ONCE, near the start of your program.
From the documentation
"Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand."
The random number generator doesn't just pull random numbers out of nowhere. When you seed it you're giving it a good number to start with, and from there it can generate a bunch of random numbers.
The problem is, it will give you a sequence of random numbers, but that sequence will be the same if you give it the same seed twice in a row. That's why it's important that the value you seed it with is relatively random. And hey, the time is pretty random, what are the chances two people will end up running the program at exactly the same time?
What you're doing, is seeding the generator before every call to rand, instead of seeding it at the beginning and letting the random number generator do its job. Since time only returns the time in seconds (see man page), you'll get the same number every time the loop runs until the start of the next second.

Resources