This question already has answers here:
Why do I always get the same sequence of random numbers with rand()?
(12 answers)
Closed 3 years ago.
I want to randomize variables a and b to output a random number 1 through 4 in the format of a,b. However, when I run my following code, the output is always the same no matter how many times I run it. For example, the output is always: 4,3 (same output shown 10 times.)
What did I do wrong here? Can someone point me in the right direction?
Thanks!
#include <iostream>
using namespace std;
int main()
{
int x;
int a, b;
a= rand() % 4 + 1;
b= rand() % 4 + 1;
x = 0;
while (x < 10) {
x++;
cout << a << "," << b << endl;
}
return 0;
}
You need to set the time seed first then call rand() otherwise you'll get always the same values:
int a, b; //store random number
std::srand(std::time(0)); // set the time seed
for(int i = 0; i != 10; ++i)
{
a = rand() % 4 + 1;
b = rand() % 4 + 1;
cout << a << "\t" << b << endl;
}
Don't forget to include <ctime> header.
What did I do wrong here? Can someone point me in the right direction?
Thanks!
You are setting a and b once and therefore they have the same value. To fix this, set them inside the loop to give them a new value each iteration:
while (x < 10) {
x++;
a = rand() % 4 + 1;
b = rand() % 4 + 1;
cout << a << "," << b << endl;
}
If you don't want the same values each time, you can call
srand(time(0)); // before the loop
Related
I'm trying to solve Codewars task and facing issue that looks strange to me.
Codewars task is to write function digital_root(n) that sums digits of n until the end result has only 1 digit in it.
Example: 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6 (the function returns 6).
I wrote some bulky code with supporting functions, please see code with notes below.
The problem - digital_root function works only if I put cout line in while loop. The function returns nonsense without this cout line (please see notes in the code of the function).
My questions are:
Why isn't digital_root working without cout line?
How cout line can effect the result of the function?
Why does cout line fix the code?
Thanks a lot in advance! I'm a beginner, spent several days trying to solve the issue.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int getDigit (int, int);
int sumDigits (int);
int digital_root (int);
int main()
{
cout << digital_root (942); // expected output result is 6 because 9 + 4 + 2 = 15 -> 1 + 5 = 6
}
int getDigit (int inputNum, int position) // returns digit of inputNum that sits on a particular position (works)
{
int empoweredTen = pow(10, position-1);
return inputNum / empoweredTen % 10;
}
int sumDigits (int inputNum) // returns sum of digits of inputNum (works)
{
int sum;
int inLen = to_string(inputNum).length();
int i = inLen;
while (inLen --)
{
sum += getDigit(inputNum, i);
i --;
}
return sum;
}
int digital_root (int inputNum) // supposed to calculate sum of digits until number has 1 digit in it (abnormal behavior)
{
int n = inputNum;
while (n > 9)
{
n = sumDigits(n);
cout << "The current n is: " << n << endl; // !!! function doesn't work without this line !!!
}
return n;
}
I've tried to rewrite the code from scratch several times with Google to find a mistake but I can't see it. I expect digital_root() to work without any cout lines in it. Currently, if I delete cout line from while loop in digital_root(), the function returns -2147483647 after 13 seconds of calculations. Sad.
Here is an implementation using integer operators instead of calling std::to_string() and std::pow() functions - this actually works with floating-point numbers. It uses two integer variables, nSum and nRem, holding the running sum and remainder of the input number.
// calculates sum of digits until number has 1 digit in it
int digital_root(int inputNum)
{
while (inputNum > 9)
{
int nRem = inputNum, nSum = 0;
do // checking nRem after the loop avoids one comparison operation (1st check would always evaluate to true)
{
nSum += nRem % 10;
nRem /= 10;
} while (nRem > 9);
inputNum = nSum + nRem;
std::cout << "The current Sum is: " << inputNum << endl; // DEBUG - Please remove this
}
return inputNum;
}
As for the original code, the problem was the uninitialized sum variable, as already pointed out by other members - it even generates a compiler error.
int sumDigits (int inputNum) // returns sum of digits of inputNum (works)
{
int sum = 0; // MAKE SURE YOU INITIALIZE THIS TO 0 BEFORE ADDING VALUES TO IT!
int inLen = to_string(inputNum).length();
int i = inLen;
while (inLen --)
{
sum += getDigit(inputNum, i);
i --;
}
return sum;
}
Initialize your variables before adding values to them, otherwise you could run into undefined behaviour. Also for the record, adding the cout line printed out something, but it wasn't the correct answer.
I am having troubles in making shapes moving in random directions, with the code that i currently have they all move in the same direction and then change to another direction randomly.
Here is the code
for(int i = 0; i < 50; i++)
{
int randomMoveX = rand() % 2 + (-1);
int randomMoveY = rand() % 2 + (-1);
circleObjectArray[i].move(randomMoveX,randomMoveY);
while(randomMoveX == 0)
{
randomMoveX = rand() % 2 + (-1);
}
while(randomMoveY == 0)
{
randomMoveY = rand() % 2 + (-1);
}
cout << "randomMoveX: " << randomMoveX << endl;
cout << "randomMoveY: " << randomMoveY << endl;
}
How can i change my code to be able to do move them in random directions individually?
Thank you for your time :D
When you run your app, a seed is set for random as srand(1).
To use different value in rand you need to change the seed of random.
Then use the function srand and save it in a unsigned int to use different rand for different shape.
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 5 years ago.
Improve this question
So as the title says,I have to write a number as sum of ascending powers of 2.
For instance, if I input 10, 25 , 173
10 = 2 + 8
25 = 1 + 8 + 16
173 = 1 + 4 + 8 + 32 + 128
So this is what I have done:
#include <iostream>
using namespace std;
int x,c;
int v[500];
void Rezolva(int putere)
{
if(putere * 2 <= x)
Rezolva(putere * 2);
if(x - putere >= 0)
{
c++;
v[c] = putere;
x -= putere;
}
}
int main()
{
cin >> x;
c = 0;
Rezolva(1);
for(int i = c; i >= 1; i--)
cout << v[i] << " ";
return 0;
}
I have a program which gives my code some tests and verifies if it's correct. To one test, it says that I exit the array. Is there any way to get rid of the array or to fix this problem ? If I didn't use the array it would have been in descending order.
The error isn't a compiler error.
Caught fatal signal 11 is what I receive when my program checks some tests on the code
For values higher than 10^9 the program crashes so you need to change from int to long long.
#include <iostream>
using namespace std;
long long x,c;
long long v[500];
void Rezolva(long long putere)
{
if (putere * 2 <= x)
Rezolva(putere * 2);
if (x - putere >= 0)
{
v[c++] = putere;
x -= putere;
}
}
int main()
{
cin >> x;
c = 0;
Rezolva(1);
for(int i = c - 1; i >= 0; i--)
cout << v[i] << " ";
return 0;
}
All in all, a simple overflow was the cause.
It was a simple overflow. And by the way a way easier way to do it is have a long long unsigned int
#include <bitset>
unsigned long long x = input;
std::cout << x << " = ";
std::string str = std::bitset<64>(x).to_string();
for (int i = str.size()-1; i >= 0; --i)
if(str[i]-'0')
std::cout << (2ull << i) << " + ";
if (x)
std::cout << char(8)<<char(8) << std::endl; //DELETING LAST "+" for non-zero x
else
std::cout << "0\n";
If you have a fixed size integer (e.g. int etc.) then you can just start at the greatest possible power of two, and if your number is bigger than that power, subtract the power of 2. Then go to the next power of two.
This is similar to how you would normally write numbers yourself starting from the most significant digit. So also works for how numbers are printed in base 16 (hex), 10, binary literals, etc.
int main() {
unsigned x = 173;
std::cout << x << " = ";
bool first = true;
// get the max power from a proper constant
for (unsigned power = 0x80000000; power > 0; power >>= 1)
{
if (power <= x)
{
if (!first) std::cout << " + ";
std::cout << power;
x -= power;
first = false;
}
}
assert(x == 0);
std::cout << std::endl;
}
Outputs:
173 = 128 + 32 + 8 + 4 + 1
I'd like to write a program in C++, which will present 6 random numbers from 1 to 54. Below you could find the code. For some strange reason, when I run the program, I sometimes stumble upon an output like this:
Bugunku sansli loto sayiniz: 17 1 12 32 33 3418568
I couldn't figure out why the last number ignores my rule.
Any help would be appreciated.
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
cout << "Bugunku sansli loto sayiniz: " << endl;
srand(time(0));
int myArray [5];
for (int i = 0; i < 6; i++)
{
myArray [i] = (rand() % 55) + 1;
cout << myArray [i] << '\t';
}
}
I couldn't figure out why the last number ignores my rule.
Because the last number accessed in the for loop is getting out of the bound of the array, dereference on it leads to UB. The for loop should be
for (int i = 0; i < 5; i++)
~
Then i will be 0 ~ 4, loop 5 times, not 6 times as your code shown.
You might use range-based for loop (since C++11) to avoid such kind of mistake:
for (auto& i : myArray) {
i = (rand() % 55) + 1;
cout << i << '\t';
}
random numbers from 1 to 54
So this is incorrect as well: (rand() % 55) + 1;
You'll need (rand() % 54) + 1;
Because you went to myArray[5] at the last time and your array don't have this place so you got it
you need to write like that:
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
cout << "Bugunku sansli loto sayiniz: " << endl;
srand(time(0));
int myArray [5];
for (int i = 0; i < 5; i++)
{
myArray [i] = (rand() % 55) + 1;
cout << myArray [i] << '\t';
}
}
If you want 6 items you need to make a array for six items
int myArray[5];
this will provide 5 items where as
int myArray[6];
this will provide you 6 items
This will fix your problem
I'm looking for a way to generate a 4 digit number with digits from 1 to 6 like 1234, 1251, 3243 ... and so on.
I want it for my makeDigitsToGuess() method in my MastermindDigits class. Every time a user starts the game, this function should be called and generate a 4 digit number containing only digits from 1 to 6.
This is what I've tried so far:
srand(time(0));
cout << "RANDOM NUMBER: " << (rand() % 6 + 1)
<< (rand() % 6 + 1)
<< (rand() % 6 + 1)
<< (rand() % 6 + 1) << endl;
this is how far I got on my own. The next step I was thinking about, was to create a vector in my method where I could push_back those 4x generated random numbers.
Does this make sense? Is there an easier way to code it?
I suggest this solution using the C++11's std::uniform_int_distribution.
#include <iostream>
#include <random>
#include <iomanip>
int generateFour()
{
int result=0;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 6);
for (int n=0; n<4; ++n)
{
result=result*10+dis(gen);
}
return result;
}
int main()
{
std::cout << std::setfill('0') << std::setw(4)
<< generateFour() << std::endl;
return 0;
}
You're basically generating a number in base 6, except you replace digit "0" by "6". (Or alternatively add 1 to all). Since it's a 4 digit number, there are 6*6*6*6 possibilities = 1296. So generate a number in the range [0, 1296) and print that in base 6.
const unsigned sup(6 * 6 * 6 * 6);
unsigned base6[sup];
for (unsigned i(0); i < sup; ++i)
{
base6[i] = (i / 216 % 6) * 1000 +
(i / 36 % 6) * 100 +
(i / 6 % 6) * 10 +
i % 6;
}
then your random number is base6[rand() % sup].
Why not make this easy, practically as you did in question.
std::string number;
for(int i = 0; i < 4; i++) {
number += rand() % 6 + 1;
}
std::cout << std::stoi(number);
I didn't test this code, but its the basic idea. You put everything into a string and convert it to a number. Perhaps not the best idea, but at least better than doing 4 times rand() :)
unsigned result = 0;
while(!(result / 1000)) /// while "result" doesn't consist of 4 digits
{
result = result * 10 + rand() % 6 + 1; // multiply previous result by 10, then add new digit.
}
I assume you have the same task as me (PAD2) so i can help you.
This is my function makeDigitsToGuess:
int randomNumber = 0;
int x = 3; //Numbers to guess
for (int i = 0; i <= x; i++) {
randomNumber = rand() % 6 + 1;
digits[i] = randomNumber;
}
This gives me a four digit number for the play mode.