c++ getting TwoRandomNumbers, min and max [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C++ Random number homework question
Guys, I need help (yes, last minute homework help). I'm suppose to write a function named getTwoRandomNumbers that uses two parameters to return two different random numbers. The function is suppose to accept two parameters that specify the minimum and maximum values of the random number.
I need to write data validation code that ensures that two identical random numbers will never be returned. This is what I have so far: (ANY DIRECTION IS GREATLY APPRECIATED)
Ok, I made changes and now have this:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <time.h>
using namespace std;
float getTwoRandomNumbers (int Min, int Max, int & number1, int & number2);
void main()
{
cout << "The two random numbers are " << getTwoRandomNumbers << endl;
}
float getTwoRandomNumbers (int Min, int Max, int & number1, int & number2)
{
int loopNumber, number;
for (loopNumber = 0; loopNumber <= 200 ; loopNumber ++)
{
number = rand();
if (loopNumber < 100 && number >= Min && number <= Max)
{
number1 = number;
}
if (loopNumber > 100 && number >= Min && number <= Max)
{
number2 = number;
}
return number2;
}
}

First off, you're on the right path with passing back both values through the parameters of the function. Then it seems like you're also trying to get the 2nd value back through the function return.
Since you need to get more than 1 value from the function, ignore the return value and just use the 2 parameters passed to get your return values.
Also, try thinking out the question in your head, what are you trying to do? Get 2 random values while number1 is not equal to number2
That should give you a decent start on the logic flow for getting the random numbers to pass back.

One thing for you: As I reformatted your code, it became apparent that you have a return within your for loop. That means getTwoRandomNumbers will always return after the first iteration. I'm 99.99% positive this is not what you have in mind.

Related

Why do I get the same random numbers every time I run my program? [duplicate]

This question already has answers here:
rand() returns same values when called within a single function
(5 answers)
Closed 4 years ago.
I am trying to generate random numbers (1 to 6), but every time I run my program I always get the same two numbers. Here is the code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// function prototype
int random();
// main function
int main()
{
int rand1=random();
int rand2=random();
cout << rand1 << endl;
cout << rand2 << endl;
cin.get();
return 0;
}
//function definition
int random()
{
const int MAX_NUMBER = 6;
const int MIN_NUMBER = 1;
unsigned seed=time(0);
srand(seed);
int randomNumber;
randomNumber=(rand() % (MAX_NUMBER - MIN_NUMBER + 1)) + MIN_NUMBER;
return randomNumber;
}
I'm not sure what is wrong and why I always get the same two random numbers.
Notice :
rand() returns a random positive integer in the range from 0 to 32,767. This function can be thought of as rolling a die with 32,767faces.
The numbers are generated by a mathematical algorithm which when given a starting number (called the "seed"), always generates the same sequence of numbers. Since the same sequence is generated each time the seed remains the same, the rand() function generates a pseudo-random sequence.
To prevent the same sequence from being generated each time, use
srand(x) to change the seed value.
Sample program :
/*generate 10 random numbers between 1 and 6 inclusive, without repetition of the sequence between program runs*/
#include <iostream.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
// to prevent sequence repetition between runs
srand(time(NULL));
for(int i = 1; i <=10; i++) // looping to print 10 numbers
{
cout<< 1 + rand( ) % 6; // formula for numbers
}
return 0;
}

C++ Simple Dice roll - how to return multiple different random numbers [duplicate]

This question already has answers here:
How does calling srand more than once affect the quality of randomness?
(5 answers)
Closed 5 years ago.
I am pretty new to C++ and am trying to make a simple die roll with a Die class/main.
I can get a random number within my range 1-dieSize, however, each time I "roll the dice" it just gives me the same random number. For example, when I roll this dice three times, it will cout 111 or 222 etc instead of 3 different random rolls. Any help explaining this issue would be much appreciated!
My die header is just a basic header. My issue I'm assuming is with the random function.
main:
int main()
{
// Call menu to start the program
Die myDie(4);
cout << myDie.rollDie();
cout << myDie.rollDie(); // roll dice again
cout << myDie.rollDie(); // roll again
return 0;
}
die.cpp:
Die::Die(int N)
{
//set dieSize to the value of int N
this->dieSize = N;
}
int Die::rollDie()
{
// Declaration of variables
int roll;
int min = 1; // the min number a die can roll is 1
int max = this->dieSize; // the max value is the die size
unsigned seed;
seed = time(0);
srand(seed);
roll = rand() % (max - min + 1) + min;
return roll;
}
In die.cpp I have the cstdlib and ctime included.
As melpomene suggested in the comment you should initialize the seed of the random only once at some point of the program.
The rand() function is not really a random number creator, rather a sequence of bit manipulation on the previously generated value, which starts with the first value that is generated by the seed (calling srand(seed)).
#include <iostream>
#include <cstdlib>
int rollDie()
{
int roll;
int min = 1; // the min number a die can roll is 1
int max = 6;// this->dieSize; // the max value is the die size
roll = rand() % (max - min + 1) + min;
return roll;
}
int main()
{
srand(time(0));
for(int i=0;i<10;i++)
{
std::cout << rollDie() << std::endl;
}
}
There is a good chance that you are already using C++11, so you should read and practice with the random library: http://en.cppreference.com/w/cpp/numeric/random

Issue with base converter function [duplicate]

This question already has answers here:
Strange behaviour of the pow function
(5 answers)
Closed 6 years ago.
I'm helping a friend with a C++ assignment. There is an issue with the folowing base converter function:
#include <iostream>
#include <cmath>
using namespace std;
int strToInt(string num, unsigned base){
int result = 0;
for (int i=0; i<num.length(); i++) {
if (num[i]>='0' && num[i]<='9')
result += (num[i]-'0')*pow(base,num.length()-i-1);
else if (num[i]>='A' && num[i]<='F')
result += (num[i]-'A'+10)*pow(base,num.length()-i-1);
else if (num[i]>='a' && num[i]<='f')
result += (num[i]-'a'+10)*pow(base,num.length()-i-1);
}
return result;
}
int main()
{
string number;
int base;
while(number.compare("exit")!=0){
cin>>number;
cin>>base;
cout<<strToInt(number,base)<<"\n\n";
}
return 0;
}
For some inexplicable reason every time I enter 3 and 5 digit decimals and chose base 10 I am getting the proper number -1.
E.g.
100
10
99
10000
10
9999
I've been going over this function for the last 5-6 hours and adding all types of debug code, but for the good of me I can't figure out what the hell is wrong.
Code style remarks are also very appreciated.
Cheers
std::pow does floating-point math. You're probably getting a round-off error somewhere. The usual way to accumulate values is to multiply and add each time through the loop:
result *= base;
result += ch - '0';

Optimizing a recursive function

I'm creating a program that returns the least quantity of sums required to get to a number (n) using only 1, 2, 6 and 13. It works perfectly for small values of n, but once n gets to values like 200 it takes the program too much time to calculate the result.
Therefore, I have two questions:
1. Is there any way to make the recursion faster?
2. Should I avoid using recursion and use a loop instead?
Here's the commented code:
#include <iostream>
#define MAX 500000
using namespace std;
void cal(int inp, int &mini, int counter = 0);
int main (void)
{
//Gets input
int n;
cin >> n;
//Defines mini as the MAX result we can get
int mini = MAX;
//Calls the function
cal(n, mini);
//Prints the best result
cout << mini << endl;
return 0;
}
void cal(int inp, int &mini, int counter)
{
//Breaks recursion if it finds an answer
if(!inp)
{
if(counter<mini) mini = counter;
return;
}
//Breaks recursion if the input is negative
//or the counter is more than the best result
else if((inp<0) || (counter>mini)) return;
//Counts amount of recursions
counter++;
//Tries every combination
cal(inp-13, mini, counter);
cal(inp-6, mini, counter);
cal(inp-2, mini, counter);
cal(inp-1, mini, counter);
return;
}
Thank you
The problem is your brute force. Let me suggest something better:
Preliminaries: If you have two 1s, it is always better to use a 2. If you have three 2s, it is better to use a 6. If you have thirteen 6s, it is better to use six thirteens.
So the any admissable sum will always look like n = 13m+k where k is written as a sum of 1, 2, and 6. With the preliminaries, we know that for the optimal sum k will never exceed 1+2*2+12*6 = 77. (The reverse doesn't hold. Not any number below 78 is best written without 13s of course.) So brute forcing those is good enough. You can then use a lookup table.
This could still be optimized further, but it should not break down at 200.
Assuming you have found your first 77 entries (which can be optimized as well) you can do this (still unoptimized ;-):
int num_13 = ((n-78) / 13) + 1;
int sum_length = MAX;
for (i = num_13; i*13 < n; i++) {
int tmp = entries_77[n-i*13]+i;
if (tmp < sum_length) {
num_13 = i;
sum_length = tmp;
}
}
I would be even quicker to compile an array for the equivalence classes modulo 13, since for any given equivalence class any number exceeding 78 will have the same k.
You can use DP (Dynamic Programming) approach to solve your problem. It's well known Coins Problem
Your recursion needs a memoization to avoid repetitive calculation. And no need for the second and third parameter of the recursion. I have updated and put explanation on your code. Let me know if you have any confusion.
#include <iostream>
#include <string.h>
#define INF 999999
using namespace std;
int cal(int inp);
int mem[502];
int main (void)
{
//Gets input
int n;
cin >> n;
//initialzing the array for using with memoization
memset(mem,-1,sizeof(mem));
//Calls the function
//Prints the best result
cout << cal(n) << endl;
return 0;
}
//returns the minimum quantity of sum operations to get inp.
int cal(int inp)
{
//Breaks recursion if it finds an answer.
//Return cost 0. As in this stage no processing was done.
if(!inp)
return 0;
// Returning infinite cost for invalid case.
if(inp < 0)
return INF;
int _ret = mem[inp];
// If already visited here before then no need to calcuate again.
// Just return previous calculation. This is called memoisation.
// If not visited then _ret would have equal to -1.
if(_ret >=0 )
return _ret;
_ret = INF;
//Tries every combination and takes the minimum cost.
_ret = min(_ret, cal(inp-13)+1);
_ret = min(_ret,cal(inp-6)+1);
_ret = min(_ret,cal(inp-2)+1);
_ret = min(_ret,cal(inp-1)+1);
// Updating the value so that can be used for memoization.
mem[inp] = _ret;
return _ret;
}
This will also work for larger numbers. Complexity is 4*n.

finding the number of perfect squares in the given range

I am trying to find out the number of perfect squares in the given range. The method I am following is provided on: digital_root
The code I have implemented is not giving correct answers sometimes because This method does not consider the numbers like 10,1000 etc.
Please help me to work out this method.
int cot=0;
void squares(int a,int b){
if(a==b){
int digit,digit_root=0,no;
no=a;
digit=no%10;
if(digit==2||digit==3||digit==7||digit==8){
}else{
no=a;
while(no>0){
digit=no%10;
if((digit==0)||(digit==9)){
}else{
digit_root=digit_root+digit;
digit_root=digit_root%9;
}
no=no/10;
}
if(digit_root==0||digit_root==7||digit_root==1||digit_root==4){
if(digit_root==1){
if(a)
}
cot++;
}
}
}else{
int c=(a+b)/2;
squares(a,c);
squares(c+1,b);
}
}
int main() {
int a,b,t;
cin>>t;
for(int i=0;i<t;i++){
cin >> a>>b;
squares(a,b);
cout << cot<<endl;
cot=0;
}
return 0;
}
the best algorithm will probably be to subtract sqrt(bigger number) - sqrt(other num), i.e. something like this
int a = 1,b=100;
if (sqrt(a) != int(sqrt(a)){
cout<<int(sqrt(b))-int(sqrt(a))<<endl;}
else{
cout<<int(sqrt(b))-int(sqrt(a))+1<<endl;}
the logic is very simple, perfect square is natural num * the same natural num so, 1*1,2*2,3*3,4*4 and so on
So you just need to get the closest perfect sqrt of the bigger num and subtract it with the smaller num (just be careful in case that the smallest num is a perfect square itself)
There's too much going on here. Simplify it. Write a function that determines whether a single number is a perfect square. Get that working right. Then use that function to determine how many perfect squares there are in your range. That probably shouldn't be recursive; that's just too hard to follow. Use a loop that covers the range:
for (int i = a; i <= b; ++i)
if (is_perfect_square(i))
++count;
It's easy to print numbers from 1 to N, and the numbers will be perfect square.
Here is the logic to check perfect square
/*function definition to check perfect square*/
int isPerfectSquare(int number)
{
int iVar;
float fVar;
fVar=sqrt((double)number);
iVar=fVar;
if(iVar==fVar)
return 1;
else
return 0;
}
You dont need all these costly calculations.
Things are really simple here.
Instead of looping from A to B and checking for perfect squares,
we can calculate the first integer square root of A at O(1) and
count the rest perfect squares with simple increments of power n,
up to B. In this way we can avoid costly calculations.
But even better, we can even avoid loops by just using ceil and floor.
For example, square numbers between 1000 and 2000:
sqrt(1000) = 31.6 --> ceil(31.6) --> 32
sqrt(2000) = 44.7 --> floor(44.7)--> 44
therefore the difference of these two plus one gives us the number of perfect squares.
#include <cmath>
#include <iostream>
using namespace std;
int main() {
int A, B;
//get the range [A,B]
cin >> A >> B;
cout << floor(sqrt(B)) - ceil(sqrt(A)) + 1 << end;
return 0;
}