Random Boolean Value [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to generate a random int that is either 0 or 1 in C++. Right now, I receive a 0 every time I run this code, and I'm not sure why. What's the problem here?
#include <ctime>
#include <cstdlib>
srand(time(0));
int randomval = rand() % 2;
cout << randomval << endl;

It is called bad luck. Try it again.

I know this is an older question but I believe this answers the question properly.
Don't re-seed the the generator every time you run that code.
By seeding it to the same value every time, you're just gonna get the same "random" number. Remember this is a Pseudo-Random number generator, so based on the seed value, a "random" number will be generated. So if you seed it with the same number every time you're just gonna get the same number every time.
The solution is to call srand(time(NULL)) only once in your program execution. Then, each call to rand() will give you a different number every time.

On theory, there's 50% chance you get 0, and 50 - 1. You may want to try with different modulo - for example 100, to check if this works. And I'm sure it does.
You have just ran this code a few times, not enough.
Other idea to test it:
srand(time(0));
for( int i = 0; i < 1000000; ++i )
{
assert( 0 == ( rand() % 2 ) );
}

I would like to add that when you use srand(time(0)); the "random number" will always be the same in the same second. When I tried to run your program 10000 times and group it by uniq I saw that the number would not change within a second.
for i in `seq 1 10000`; do ./a.out; done | uniq -c
693 0
3415 1
675 0
673 1
665 0
674 1
668 0
711 1
694 0
673 1
459 0

bool random() {
if (rand() % 2 == 0)
return true;
else return false;
}

Call srand(time(NULL)); just once.
Then use a loop like this, you will always get a 0 or 1 this way.
#include <stdio.h>
#include <stdlib.h>
srand(time(NULL));
for (i=0;i<10;i++)
{
printf("%d\n",rand() % 2);
i++;
}
return 0;

Although your code suggests that you want to receive them equally likely, you didn't state that, and perhaps you have simply thought that it was impossible to do otherwise. If you want a different distribution, and you are willing to rewrite your code (and make it C++11 compliant), you can do the following:
const double chance = 0.3; // this is the chance of getting true, between 0 and 1;
std::random_device rd;
std::mt19937 mt(rd());
std::bernoulli_distribution dist(chance);
bool result = dist(mt);
If you will need to do that in a loop, only repeat the last statement dist(mt), keep all the generated objects as they are without recreating them.

You are not checking against anything. Use:
#include <ctime>
#include <cstdlib>
srand(time(0));
int randomval = rand() % 2 == 0;
cout << randomval << endl;

Related

Want to see if a one digit of a 2 digit number is divisible by the other digit [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 11 months ago.
Improve this question
The problem I am having is how to say if(//code=Whole) I dont know how to tell the program if the number equals whole number because if its a number like 39 9 divided 3 equals a whole number if a number is not divisible it will go to the decimals which is how I am willing to solve the problem by saying if digit 1 or 2 divisible by the other digit is whole then cout<<Divisible
I tried searching up didnt work heres my code
#include <iostream>
using namespace std;
int main()
{
int x,z,n;
cin>>x;
x%10=z;
x/10=n;
if(z/n==int)
{
cout<<"YES";
}
else if(n/z==int)
{
cout<<"YES"
}
else
{
cout<<"NO";
}
}
I dont know how to say if it equals whole So i dont know what to put there plus there might be something wrong in the program other than that.
This is your code.
int main()
{
int x,z,n;
cin>>x;
x%10=z;
x/10=n;
if(z/n==int)
{
cout<<"YES";
}
else if(n/z==int)
{
cout<<"YES"
}
else
{
cout<<"NO";
}
}
A few things. First, please use whitespace to make your code readable. It's going to safe you from a wide variety of bugs over the years.
Next, this is bad code:
x%10=z;
x/10=n;
So is this:
if(z/n==int)
The first few lines of your main method should be like this:
int x;
cin >> x;
int z = x % 10;
int n = x / 10;
Note that I've done two things. First, I moved where the variables are declared to as late as possible so that they aren't hanging around, uninitialized for a while. This is just good practice. Define them and assign them at the same time.
Next, the way you wrote that code doesn't make sense. An assignment statement can't be written backwards the way you did it.
In your head, you could say, "z becomes x % 10" if you have to.
This line won't compile:
if(z/n==int)
If you want to see if z divides evenly by n:
if ( z % n == 0 )
You have the same problem in the else-if a few lines later.

Why does rand()%10+1 give me a number between 1-10? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Im fairly new to programming
So i was actually trying to figure something out
Why does rand()%10+1 give us a number between 1-10 whereas 32767%10 is actually 7?
I think I see the source of your confusion.
The fact that you referred to rand()%10 in your title and rand()%10+1 in the body of your question made that difficult.
You asked:
Why does rand()%10+1 give us a number between 1-10 whereas 32767%10 is actually 7?
It's because the function N%10 is not monotonically increasing. As the value of N increases, the value of N%10 goes up and down.
I think you're assuming:
that 32767 is the maximum value returned by rand() (which it can be, but on my system it's 2147483647, but that doesn't affect the point); and
that if 32767 is the maximum value returned by rand(), then 32767%10, which is 7, must be the maximum value of rand()%10.
Your second assumption is wrong. For any value N (we'll ignore negative values), N%10 is the last digit of its decimal representation. If rand() returns 9, then rand()%10 will be 9 and rand()%10+1 will be 10 -- which is larger than the value of 32767%10+1.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int randomnumber;
randomnumber = rand() % 10;
printf("%d\n", randomnumber);
return 0;
}
When you run this code it will generate a number from 0 to 10 because of number 10 behind it (Because you want to random to 10 so that is why is a 10) but it will generate from 0 to 9 only. That's why you need a +1 at the end to generate random from 1 to 10. That's all.

Program to check if we can make odd sum out of numbers [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
So basically this program takes several test cases which consist of a sequence of numbers (of length n). It's supposed to see that, if there exists at least one combination of length x out of the sequence, so that their sum will be odd. It's enough for just one of such combinations to exist. If it's possible, we print "Yes", otherwise "No".
For example, if we input
1 (t=1, one test case)
3 2 (n=3, aka 3 total nrs, x=2, aka consider any 2 of these)
16 11 12 (these are the numbers)
2 even nrs, 1 odd. 11+12 is odd, so the output will be Yes.
My problem is this case particularly
3 3
101 102 103
If I check it on its own, meaning just this one test case, it outputs the correct "No".
If it's with other test cases, meaning it's test 2 or lower, it outputs "Yes".
Can anyone tell me why?
I would really appreciate it.
Here's the code.
#include <iostream>
using namespace std;
int main()
{
int t, n, x, k, c_even{ 0 }, c_odd{ 0 };
string v{"No\n"};
cin >> t;
//t is the number of total cases
for (int i = 1; i <= t; i++)
{
c_even = 0; //counter for even numbers
c_odd = 0; // counter for odd numbers
cin >> n >> x; // n is the total length of the sequence of nrs, x is how many numbers we consider out of the sequence
//this for loop is for introducing the sequence and counting how many nrs are odd and even
for (int j = 1; j <= n; j++)
{
cin >> k;
if (k % 2 == 0)
c_even++;
else c_odd++;
}
//obv if there are no odd nrs, sum won't ever be odd
if (c_odd == 0)
v = "No\n";
/*
for example, say we have 5 odd numbers, 3 even, and we have to consider 5 numbers out of total 8.
the for loop starts with 1. it checks if 1+3>=5, meaning if we have enough even nrs to make odd sum. it's not correct in this case.
then it goes to o=3; it checks if 3+3>=5. correct! so we have enough even nrs to make odd sum. other cases don't have to be considered.
*/
else for (int o = 1; o <= c_odd; o += 2)
{
if (o + c_even >=x)
{
v = "Yes\n";
break;
}
}
cout << v;
}
}
Just had to move string v{"No\n"}; inside the first for.
As cigien said, if string v{"No\n"}; is outside the first loop, in case one iteration sets v as "Yes" and the next one does not satisfy
if (c_odd == 0)
v = "No\n";
in other words, the v remains "Yes", the program will output automatically "Yes", although it is not the correct answer.
By moving that bit of code inside the first for, we assure that each iteration will start with v as "No".

Loop doesn't end. How do I get out of a loop? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to generate and print out 5 numbers from 1 to 5, but not in sequence. I'm using a self-written function, 'appearBefore' that will check whether the number has appeared before.
The function appearBefore will return '0' if the number has not appeared before, and '1' if the function has appeared before.
At the moment, the do-while loop doesn't get out of the loop even when 0 is returned. The program never ends. Any recommendations on what I can do?
EDITS - The downvotes sure comes fast. I have added the counter++, but it still does not work. Perhaps someone can advice on the inner-loop?
while (count < 5) {
repeat = 1;
do {
randomNumber = rand() % 4 + 1;
cout << randomNumber;
repeat = appearBefore(randomNumber);
cout << " " << repeat << endl;
} while (repeat == 1);
//Add the number into an array of numbers that have appeared before
checker[counterForChecker] = randomNumber;
counterForChecker++;
counter++;
}
This is the function appearBefore (the variables are global variables):
int appearBefore(int number) {
int x = 0;
int match = 0;
while (x < counterForChecker+1) {
if (checker[x] == number) {
match = 1;
break;
}
else {
match = 0;
}
x++;
}
return match;
}
You check for count < 5 while increasing counterForChecker.
Set the while condition to
while (counterForChecker < 5)
or increase the counter
counter++; // counterForChecker++;
(Assuming that counter++; actually says count++;...)
If x and k are positive, x % k is a number between 0 and k - 1.
So you have four possible values to choose from (1,2,3,4), and you're looping until you've found five unique values.
That will never end well.
To generate numbers from 1 to 5, use rand() % 5 + 1;
You'll want to change the variable count. This is now not done, so since the value does not change the loop will not end.
The loop is running while count < 5 and you never increment count.
Did you mean to use:
while (counterForChecker < 5)
If not, add:
++count;
at the end of the while loop
Use a debugger and step through the code, looking at the values of the variables as you do so. You'll learn more about how everything is working.

Random Number Generator mechanism

i had the following problem in my book:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
clrscr();
randomize();
int Game[]={10,16},P;
int Turn=random(2)+5;
for(int T=0;T<20;T++)
{
P=random(2);
cout<<Game[P]+Turn<<"#";
}
getch();
}
The output comes like 16#22#16#16#16#22#....20 times...
Why the output of this always comes either 16# or 22#?? why not 15# or 21#?? i would like to the mechanism of this program. Thanks.
turn=random(2)+5;
if random(2) gives 0 then turn becomes turn=0+5=5 which implies that i should get 10+5=15 and 16+5=21 along with 16 and 22 but i m not getting them.
We got the above question in our computer science theory exam and we were to chose the correct answer(i.e it generates 16 and 22) but how will i am going to know that it will generate only 16 and 22. As i explained above 15 and 21 are also possible..
maybe this helps:
The seed for the random number generator is not set.
If you call srand(time(NULL)) then you will get more random results
C++ rand() gives same number when running process
You need to give a seed value that would help get "really" random. mumbers
A computer cannot randomize numbers by itself, it uses a seed for that.
But seed's aren't completely random they just have a specific order, like:
1
2
8
5
4
These numbers look pretty random but when you run the program the next time you will get:
1
2
8
5
4
The exact same.
To prevent this we use the time as a seed, time always changes so it will always generate new numbers.
#include <time.h>
srand(time(NULL)); // srand is the function to randomize numbers from a seed, we use 'time' as seed here
this video explains it.
Because Turn is only randomized once - at the beginning of the loop. If you move the assignment of Turn into your loop, you should get 15 and 21 also:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
clrscr();
randomize();
int Game[]={10,16},P;
int Turn;
for(int T=0;T<20;T++)
{
P=random(2);
Turn=random(2)+5;
cout<<Game[P]+Turn<<"#";
}
getch();
}
Also, as said by others, if you want the output to differ between runs, you will need to seed your random number generator, for instance by calling srand() with a seed. For instance:
#include <time.h>
(...)
srand(time(NULL));