I want to generate random numbers inside loop but results are always same numbers.
What I'm doing wrong? Thanks.
Code
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;
const char duom[] = "U1.txt";
const char rez[] = "U1_rez.txt";
void num_gen(int & x, int & y);
int main(){
srand(time(NULL));
int x, y;
ifstream fd(duom);
fd >> x >> y;
fd.close();
ofstream fr(rez);
for(int j = 1; j <= 4; j++){
num_gen(x, y);
fr << x << " + " << y << " = "<< x + y << endl;
fr << x << " - " << y << " = "<< x - y << endl;
fr << x << " * " << y << " = "<< x * y << endl;
fr << x << " / " << y << " = "<< x / y << endl;
fr << "************" << endl;
}
fr.close();
return 0;
}
void num_gen(int & x, int & y){
x = 3 + (rand() % 10);
y = 3 + (rand() % 10);
}
Result
4 + 8= 12
4 - 8= -4
4 * 8= 32
4 / 8= 0
************
4 + 9= 13
4 - 9= -5
4 * 9= 36
4 / 9= 0
************
9 + 11= 20
9 - 11= -2
9 * 11= 99
9 / 11= 0
************
12 + 8= 20
12 - 8= 4
12 * 8= 96
12 / 8= 1
************
With the advent of C++11/14 you should actually give up using srand & rand & use the more efficient RANDOM NUMBER GENERATING MACHINES declared in the header #include<random>. Illustrating in a simple example :-
#include <iostream>
#include <random> // for default_random_engine & uniform_int_distribution<int>
#include <chrono> // to provide seed to the default_random_engine
using namespace std;
default_random_engine dre (chrono::steady_clock::now().time_since_epoch().count()); // provide seed
int random (int lim)
{
uniform_int_distribution<int> uid {0,lim}; // help dre to generate nos from 0 to lim (lim included);
return uid(dre); // pass dre as an argument to uid to generate the random no
}
int main()
{
for (int i=0;i<10;++i)
cout<<random(10)<<" ";
return 0;
}
One of the outputs of the above code is :-
8 5 0 4 2 7 9 6 10 8
See, the numbers vary from 0 to 10. Give your limits in uniform_int_distribution according to your desired output. This thing seldom fails & you can generate random numbers in greater ranges without worrying about outrageous outputs like you had.
Might be because the the random method is running with time of the computer. So if in the same 1/10000 of a second you computer do all process he need to do, you might read the same number since the random method haven't refresh the value. Try to put a sleep at the end of the for (like sleep(100)) and check if the values changed.
I think your code should generate different "pseudo" random numbers between 3 and 12 at each run, subject to that more of one second has elapsed between each run. Check if all this is really what you want.
Maybe you just run it much faster than the increase in a second when you call to time(NULL), which return the number of seconds since the epoch.
Anyway, your random numbers are not very good because you use the lower order bits. I transcript this excerpt from the rand() man page:
In Numerical Recipes in C: The Art of Scientific Computing (William H.
Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling; New
York: Cambridge University Press, 1992 (2nd ed., p. 277)), the follow-
ing comments are made:
"If you want to generate a random integer between 1 and 10, you
should always do it by using high-order bits, as in
j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));
and never by anything resembling
j = 1 + (rand() % 10);
(which uses lower-order bits)."
Related
The rod cutting problem is as follows:
Given a rod of length n inches and a table of prices pi for i = 1, 2, ..., n, determine the maximum revenue Rn obtainable by cutting up the rod and selling the pieces. Note that if the price Pn for a rod of length n is large enough, an optimal solution may require no cutting at all.
Consider the following example:
length i 1 2 3 4 5 6 7 8 9 10
price pi 1 5 8 9 10 17 17 20 24 30
Consider the case when n = 4. Cutting a 4-inch rod into two 2-inch pieces produces revenue p2 + p2 = 5 + 5 = 10, which is optimal.Write a program for solving the problem from above such that the time complexity is not higher than Θ(n^2). Your solution has to determine the optimal revenue without the listing of the cuts.
I have developed the following code:
#include <iostream>
#include <stdio.h>
#include <limits.h>
using namespace std;
int max(int a, int b) {return (a > b)? a : b;}
int cutRod(int price[], int n){
int r[n+1];
r[0] = 0; //solution array
for (int i = 1; i <= n; i++){
int q = INT_MIN;
for( int j = 1; j <= i; j++) {
q = max(q, price[j-1] + r[i-j]);
r[i] = q;
}
}
return r[n];
}
int main() {
int price[] = {1, 5, 8, 9, 10, 17, 20, 24, 30};
cout << cutRod(price, 1) << endl;
cout << cutRod(price, 2) << endl;
cout << cutRod(price, 3) << endl;
cout << cutRod(price, 4) << endl;
cout << cutRod(price, 5) << endl;
cout << cutRod(price, 6) << endl;
cout << cutRod(price, 7) << endl;
cout << cutRod(price, 8) << endl;
cout << cutRod(price, 9) << endl;
cout << cutRod(price, 10) << endl;
return 0;
}
I get no errors during compilation, but when I run it the outcome is the following:
1
5
8
10
13
17
20
24
30
32766
which means that for n = 9 and for n = 10, we have that the max revenue is 30 and 32766 respectively. This is wrong as the max revenue for n = 9 is 24 and n = 10 is 30. I have tried re structuring the for loop but I am not able to correct this. My question here is what part of the code is incorrect for the revenues for n => 8 to be incorrect. Any help is much appreciated!!!
You have 9 elements in your array... (Off-by-one)
Also, as a side note, you should use the C++ algorithms instead of your own max function (std::max is in <algorithm>), and in C++ code don't use .h system headers (use their C++ equivalent, so here they would be cstdio, which you don't actually use here, and climits).
As a second side note, you should respect constness (so put a const in front of the int price[] in the argument list, it may show some bugs).
As a third side note, instead of INT_MIN you can just use 0.
As a fourth side note, maybe use std::array? (Though that is purely optional and a matter of preferences! You may need an array, in which case, nevermind.)
As a final side note, since array are 0-indexed in C/C++, you should make your loops start at 0 and not 1 (though once again that is a matter of preferences).
(PS: I just noticed, in the example you provided above you have a 17 twice in the prices, for 6 and 7 units of length.)
This question already has answers here:
Generating a random integer from a range
(14 answers)
Closed 6 years ago.
I need help figuring out how to generate a set amount of random numbers between two user-inputted values, inclusively. Just so you know, I have searched for this but am not finding what I have just stated. Here is my code:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
int userBeg, userEnd, outPut;
cout << "Enter a start value: ";
cin >> userBeg;
cout << "Enter an end value: ";
cin >> userEnd;
srand(time(NULL)); //generates random seed val
for (int i = 0; i < 5; i++) {
//prints number between user input, inclusive
outPut = rand()%((userEnd - userBeg) + 1);
cout << outPut << " ";
}//end for
return 0;
}//end main
I'm confused with the output I get for the following ranges:
1-100 yield output numbers which fall in-between, but not including, the boundaries such as 50, 97, 24, 59, 22.
But, 10-20 yield numbers such as 1, 14, 6, 12, 13. Here, the output is outside of the boundaries as well as in-between them. What am I doing wrong?
Thank you in advance for your help!
Using the c++11 random library.
You could use std::default_random_engine (or any other random engine) with std::uniform_int_distribution.
The values you pass to std::uniform_int_distribution will be the lower and upper bounds of your random range.
e.g.
#include <iostream>
#include <random>
int main()
{
const int nrolls = 100;
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(0,9);
int p[nrolls]={};
for (int i=0; i<nrolls; ++i)
{
p[i] = distribution(generator);
}
std::cout << "uniform_int_distribution (0,9):" << '\n';
for (int i=0; i<nrolls; ++i)
{
std::cout << i << ": " << p[i] << '\n';
}
}
If you wish to seed the random engine, create it like.
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator(seed);
rand returns number between 0 and RAND_MAX. By taking modulo userEnd - userBeg + 1 the boundaries will be limited to 0 and userEnd - userBeg. If the random number should be within given boundaries, then userBeg should be added, so the calculus becomes
outPut = rand()%((userEnd - userBeg) + 1) + userBeg;
It's still experimental, but it is exactly what you want
http://en.cppreference.com/w/cpp/experimental/randint
#include <iostream>
#include <experimental/random>
int main()
{
int random_number = std::experimental::randint(100, 999);
std::cout << "random 3-digit number: " << random_number << '\n';
}
Edited: it's really random http://en.cppreference.com/w/cpp/numeric/random
For the rand to work you need to do:
#include <cstdlib>
int main() {
int Min = 103;
int Max = 113;
int Number = std::rand() % (Max + 1 - Min) + Min;
return 0;
}
I omitted the cin for clarity. (Max + 1 - Min) makes it inclusive. + Min sets the minimum value!
So stuffed into a function you may use:
int randint(int Min, int Max) {
return std::rand() % (Max + 1 - Min) + Min;
}
After testing it works with negative numbers as well as positive.
Sample outputs (with a loop and cout):
11-23
The number is: 13
The number is: 18
The number is: 14
The number is: 17
The number is: 18
The number is: 18
The number is: 23
The number is: 15
The number is: 11
The number is: 22
The number is: 22
The number is: 11
The number is: 22
The number is: 16
The number is: 14
The number is: 21
The number is: 16
The number is: 19
The number is: 15
The number is: 13
The number is: 17
1239-1242
The number is: 1240
The number is: 1242
The number is: 1239
The number is: 1241
The number is: 1241
The number is: 1241
The number is: 1239
The number is: 1240
The number is: 1240
The number is: 1240
The number is: 1242
The number is: 1240
The number is: 1242
So, here is the problem:
Given a number n I need to calculate the amount of calls it would need to calculate the fibonacci of that number recursively and output only the last digit in a given base as a decimal. The input comes as 2 numbers being the first the number n and the second the base that the output should be in. For the output should be the case number, the first input, the second input and the result of the calculation. The program should exit when the first entry is equal to the second entry that equals 0. For example:
Input:
0 100
1 100
2 100
3 100
10 10
3467 9350
0 0
Output:
Case 1: 0 100 1
Case 2: 1 100 1
Case 3: 2 100 3
Case 4: 3 100 5
Case 5: 10 10 7
Case 6: 3467 9350 7631
I have arrived on the following formula when trying to solve this. Being c(n) the last digit of the number of calls it would take in a base b, we have that:
c(n) = (c(n-1) + c(n-2) + 1) mod b
The problem is that n can be any value from 0 to 2^63 - 1 so I really need the code to be efficient. I have tried doing in a iterative way or using dynamic programming but, although it give me the right output, it doesn't give me in a short enough time. Here is my code:
Iterative
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<unsigned long long int> v;
unsigned long long int x,y,co=0;
cin >> x >> y;
while(x||y){
co++;
v.push_back(1);
v.push_back(1);
for(int i=2;i<=x;i++) v.push_back((v[i-1]+v[i-2]+1)%y);
cout << "Case " << co << ": " << x << " " << y << " " << v[x] << endl;
cin >> x >> y;
v.clear();
}
return 0;
}
Dynamic programming
#include <iostream>
#include <vector>
using namespace std;
vector<unsigned long long int> v;
unsigned long long c(int x, int y){
if(v.size()-1 < x) v.push_back((c(x-1,y) + c(x-2,y) + )%y);
return v[x];
}
int main(){
int x,y,co=0;
cin >> x >> y;
while(x||y){
co++;
v.push_back(1);
v.push_back(1);
cout << "Case " << co << ": " << x << " " << y << " " << c(x,y) << endl;
cin >> x >> y;
v.clear();
}
return 0;
}
x and y are respectively n and b, v holds the values for c(n)
Every c in the sequence is less than b. So there are b possibilities for the value of a c. So a pair of consecutive elements [ck, ck+1] can have b2 possible values. So if you start at the beginning and calculate c1, c2, c3... you will have to calculate at most b2 of them before the sequence begins to repeat; you will come to a [ck, ck+1] that is equal to an earlier [cj, cj+1].
Then you know the length of the cycle, call it S, and you know that cn = c((n-j)mod S)+j for all n > j. That should cut your work down quite a lot.
My code here finds the sum of some given multiples less than or equal to a certain number. It uses a modified version of a formula I read about on the internet a while ago (the one for finding the sum of all the numbers less than or equal to 100, or 1000 or something- when I wrote my formula while I was waiting to be picked up at the ymca so it might not look like the one from the internet). So for me I used (n+x)(n/x/2), where n is the limit (for example 1000), and x is the multiple you are using (so 1, or 3, or 5). So if n = 1000 and x = 5, it should find the sum of all multiples of 5 less than or equal to 1000).
Sometimes it adds up correctly and sometimes it doesn't.
For example, if I choose 1 and 2 as the multiples, and 20 as the limit, it prints out 320 (which is correct if you add 1+2+3...+20 and then add to that 2+4+6...+20).
But if I do the multiples of 3 and 5 and 1000 as the limit, it prints out 266,998 (which is wrong according to the internet).
I do not understand why it worked in the first instance but not the second (I have only taken 1 year of high school math, I'll be a sophomore).
Here is the code:
/*
Finds the sum of all inputted multiples below a certain number
For example, it could find the sum of all the multiples of 3 and 5 less than
or equal to 1000
Written By Jay Schauer
*/
//Data Declarations
#include <iostream>
int main()
{
using namespace std;
int a; //Stores the number of multiples being used
cout << "Enter the amount of multiples you would like to use (up to 50
<< endl;
cout << "(for example, enter '2' if you would like to use two multiples,
maybe 3 and 5?)" << endl;
cin >> a;
cout << "Next, you will enter the mutliples you want to use." << endl;
cout << "(for example, if you want to find the sum of the multiples of 3
and\n5 below a given amount, enter 3 as 'multiple 1' and 5 as 'multiple
2')" << endl;
int multiples[50]; //Stores the multiples being used
for (int i = 0; i < a; i++)
{
cout << "Enter 'multiple " << (i + 1) << "'" << endl;
cin >> multiples[i];
}
int limit; //Stores the limit
cout << "Enter the the limit for how high you want to add the multiples
<< endl;
cout << "(for example, you could set the limit to 1000 to find the sum
of the\nmultiples of 3 and 5 (if you entered those) less than and or
equal to 1000)" << endl;
cin >> limit;
int sum(0); //Stores the sum
for (int i = 0; i < a; i++)
{
sum += ((limit + multiples[i]) * (limit / multiples[i] / 2));
}
cout << "The sum is "<< sum << endl;
system("pause");
return 0;
}
EDIT: I believe the problem might lie in the code not in the formula, because using it on multiples of 3 with 21 as the limit causes it to print out 72, not 84 like it should. I am still unsure of the coding error.
EDIT 2: I changed the for loop to this so it hopefully will function when the limit isn't a multiple of the multiple
for (int i = 0; i < a; i++)
{
int max = limit; /*This is done so I can change max in case it isn't
a multiple of the multiple*/
while (max % multiples[i] != 0) max--;
sum += ((max + multiples[i]) * (max / multiples[i] / 2));
}
Change
sum += ((limit + multiples[i]) * (limit / multiples[i] / 2));
to
sum += (limit + multiples[i]) * (limit / multiples[i]) / 2;
As it is, for your example of 3 and 21, you're computing (24 * (7 / 2)) = 24 * 3 = 72 (integer division of 7 by 2 gives 3, and the remainder is lost), but you want to be computing (24 * 7) / 2 = 84.
I am trying to write two loops in one for loop so I looked up the syntax for multiple variables in the for loop
the problem is the second variable l isn't updating I don't know why
#include<iostream>
using namespace std;
int main ()
{
float vsum=0, lsum=0;
double nsum=0, msum=0;
float v=1, l=100000000;
for (v, l ; v<= 100000000, l >= 1 ; v++, l--)
{
vsum= vsum + 1/v;
nsum= nsum + 1/v;
lsum= lsum + 1/l;
msum= msum+ 1/l;
}
cout << " The float sum of all numbers 1 through 1/100000000 is " << vsum << endl;
cout << " The double sum of all numbers 1 through 1/100000000 is " << nsum << endl;
cout << "The float sum of all numbers 1/100000000 through 1/1 is " << lsum << endl;
cout << "The double sum of all numbers 1/100000000 through 1/1 is " << msum << endl;
cin >> vsum;
}
I guess your question is that after
float f = 100000000;
why does --f; leave f unchanged?
The answer is due to the granularity of float. The float does not have enough accuracy to store every possible integer. Clearly a 32-bit float cannot store as many integer values as a 32-bit int, for example.
The further away from 0 you get, the larger the gap gets between successive possible values of a float. On your system 100000000 - 1 is still larger than the next possible value of float below 100000000.
The rules of C++ are that when the result of the calculation is not representable exactly by a float, then it's implementation-defined whether the next-lowest value or the next-highest value is used. (So your compiler should actually document what happens here). In this case your system is using the next-highest value.
To get your intended results, make v and l be integral types, and do a float conversion in the actual calculation, e.g.
vsum += 1.f/v;
nsum += 1.0/v;
As dasblinkenlight mentions, you are only checking the second condition, but the second variable is updating just fine. Here is an abridged example that proves this.
#include<iostream>
using namespace std;
int main ()
{
float vsum=0, lsum=0;
double nsum=0, msum=0;
float v=1, l=10;
for (v, l ; v<= 10, l >= 1 ; v++, l--)
{
cout << v << " " << l << endl;
}
}
Output:
1 10
2 9
3 8
4 7
5 6
6 5
7 4
8 3
9 2
10 1