It asks:
Modify the recursive rabbit function so that it is visually easy to follow the flow of execution. In stead of just adding "Enter" and "Leave" messages, indent the trace messages according to how "deep" the current recursive call is.
By exercising correctly adding white space(s) in the recursive rabbit function, better out understanding on how the recursion works.
This is what the program should display:
Enter rabbit: n = 4
Enter rabbit: n = 3
Enter rabbit: n = 2
Leave rabbit: n = 2 value = 1
Enter rabbit: n = 1
Leave rabbit: n = 1 value = 1
Leave rabbit: n = 3 value = 2
Enter rabbit: n = 2
Leave rabbit: n = 2 value = 1
Leave rabbit: n = 4 value = 3
I don't really have a clue to how to get the proper indentations or how to display the "leave rabbits" that have n greater than 2. So far my code is:
#include <iostream>
#include <iomanip>
int rabbit(int);
using namespace std;
int main()
{
cout << rabbit(4) << endl;
return 0;
}
int rabbit(int n)
{
cout << "Enter rabbit: n = " << n << endl;
if(n <=2)
{
cout << "Leave rabbit: n = " << n << endl;
return 1;
}
else
{
return rabbit(n - 1) + rabbit(n - 2);
}
}
Can someone point me to the right direction? Thank you very much.
EDIT:
I have it somewhat close but it is still missing the ability to display "Leave rabbit: n = 3" and "Leave rabbit: n = 4."
Here is my new code:
#include <iostream>
#include <iomanip>
int rabbit(int, int);
using namespace std;
int main()
{
int months;
cout << "How many months?" << endl << "Months ::: ";
cin >> months;
cout << rabbit(months, 0) << endl;
return 0;
}
int rabbit(int n, int parameter)
{
int value;
for(int i = 0; i < parameter; i++)
{
cout << " ";
}
cout << "Enter rabbit: n = " << n << endl;
if(n <=2)
{
for(int i = 0; i < parameter; i++)
{
cout << " ";
}
value = 1;
cout << "Leave rabbit: n = " << n << " value = " << value << endl;
return value;
}
else
{
return rabbit(n - 1, parameter + 1) + rabbit(n - 2, parameter + 1);
}
}
On SO, we try not to give code solutions to assignments, and to your credit you are only asking for hints.
The key to solving any problem is to state it well.
If you look at the required output, you can see
The output from the first call is not indented.
The output from the next call is indented 3 spaces.
The output from the next call is indented 3 more spaces.
So: what is the relationship between the number of level of calls to rabbit, and the amount of indentation?
If there were more, deeper calls to rabbit we would expect a good solution to continue to work, giving greater levels of indentation.
I think you'll kick yourself, all you need to do is use the value variable for both cases.
int rabbit(int n, int parameter)
{
int value;
for(int i = 0; i < parameter; i++)
{
cout << " ";
}
cout << "Enter rabbit: n = " << n << endl;
if(n <=2)
{
value = 1;
}
else
{
value = rabbit(n - 1, parameter + 1) + rabbit(n - 2, parameter + 1);
}
for(int i = 0; i < parameter; i++)
{
cout << " ";
}
cout << "Leave rabbit: n = " << n << " value = " << value << endl;
return value;
}
Related
I am trying to make code that gets from user, the number of inputs and value of each input and then calculate total sum of the even numbers and product of the odd numbers.
I get to put in the first number but then the for loop does not work.
#include <iostream>
#include <vector>
int main() {
int totalNum;
int total_even;
int product_odd;
std::vector<int> numbers;
std::cout << "How many numbers would you like to entre?:";
std::cin >> totalNum;
std::cout << "\n";
for (int i = 1; i <= totalNum; i++){
std::cout << "Please entre number " << i << "\n";
std::cin >> numbers[i];
if (numbers[i] % 2 == 0) {
total_even = total_even + numbers[i];
} else {
product_odd = product_odd * numbers[i];
}
}
std::cout << "Sum of even: " << total_even << "\n";
std::cout << "Product of odd: " << product_odd;
}
First off, there's no need for a vector since, once you've finished with the number, you never need to use it again. Getting rid of the vector will remove the erroneous assignment to a non-existing element (appending to a vector is done with push_back rather than assigning beyond the end).
Second, since you're either adding the number to, or multiplying the number by, some accumulator, the accumulators should be initialised. You should initiliase total_even to zero and product_odd to one, so that the operations work out (0 + a + b == a + b, 1 * a * b == a * b). As it stands at the moment, your initial values are arbitrary so your results will also be arbitrary.
By way of example, here's a possible solution (though you should edit your own program rather than use this verbatim: it's a near-certainty that educators will be checking classwork, assuming that's what this is, for plagiarism):
#include <iostream>
int main() {
int numCount, thisNum, sumEven = 0, productOdd = 1;
std::cout << "How many numbers would you like to enter? ";
std::cin >> numCount;
std::cout << "\n";
for (int i = 1; i <= numCount; i++) {
std::cout << "Please enter number #" << i << ": ";
std::cin >> thisNum;
if (thisNum % 2 == 0) {
sumEven += thisNum;
} else {
productOdd *= thisNum;
}
}
std::cout << "\nSum of even: " << sumEven << "\n";
std::cout << "Product of odd: " << productOdd << "\n";
}
A sample run:
How many numbers would you like to enter? 6
Please enter number #1: 1
Please enter number #2: 2
Please enter number #3: 3
Please enter number #4: 4
Please enter number #5: 5
Please enter number #6: 6
Sum of even: 12
Product of odd: 15
For this program a user must enter 10 contestants and the amount of second it took for them to complete a swimming race. My problem is that I must output the 1st, 2nd and 3rd placers, so I need to get the three smallest arrays (as they would be the quickest times) but I'm unsure on how to do it. Here is my code so far.
string names[10] = {};
int times[10] = { 0 };
int num[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int min1 = 0, min2 = 0, min3 = 0;
cout << "\n\n\tCrawl";
for (int i = 0; i < 10; i++)
{
cout << "\n\n\tPlease enter the name of contestant number " << num[i] << ": ";
cin >> names[i];
cout << "\n\tPlease enter the time it took for them to complete the Crawl style: ";
cin >> times[i];
while (!cin)
{
cout << "\n\tError! Please enter a valid time: ";
cin.clear();
cin.ignore();
cin >> times[i];
}
if (times[i] < times[min1])
min1 = i;
cout << "\n\n\t----------------------------------------------------------------------";
}
system("cls");
cout << "\n\n\tThe top three winners of the Crawl style race are as follows";
cout << "\n\n\t1st Place - " << names[min1];
cout << "\n\n\t2nd Place - " << names[min2];
cout << "\n\n\t3rd Place - " << names[min3];
}
_getch();
return 0;
}
As you can see, it is incomplete. I know how to get the smallest number, but its the second and third smallest that is giving me trouble.
your code is full of errors:
what do you do with min2 and min3 as long as you don't assign them?? they are always 0
try checking: cout << min2 << " " << min3;
also you don't initialize an array of strings like that.
why you use an array of integers for just printing number of input:
num? instead you can use i inside loop adding to it 1 each time
to solve your problem use a good way so consider using structs/clusses:
struct Athlete
{
std::string name;
int time;
};
int main()
{
Athlete theAthletes[10];
for(int i(0); i < 10; i++)
{
std::cout << "name: ";
std::getline(std::cin, theAthletes[i].name);
std::cin.sync(); // flushing the input buffer
std::cout << "time: ";
std::cin >> theAthletes[i].time;
std::cin.sync(); // flushing the input buffer
}
// sorting athletes by smaller time
for(i = 0; i < 10; i++)
for(int j(i + 1); j < 10; j++)
if(theAthletes[i].time > theAthletes[j].time)
{
Athlete tmp = theAthletes[i];
theAthletes[i] = theAthletes[j];
theAthletes[j] = tmp;
}
// printing the first three athletes
std::cout << "the first three athelets:\n\n";
std::cout << theAthletes[0].name << " : " << theAthletes[0].time << std::endl;
std::cout << theAthletes[1].name << " : " << theAthletes[1].time << std::endl;
std::cout << theAthletes[2].name << " : " << theAthletes[2].time << std::endl;
return 0;
}
I hope this will give u the expected output. But i suggest u to use some sorting alogirthms like bubble sort,quick sort etc.
#include <iostream>
#include<string>
using namespace std;
int main() {
int times[10] = { 0 };
int num[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int min1 = 0, min2 = 0, min3 = 0,m;
string names[10] ;
cout << "\n\n\tCrawl";
for (int i = 0; i < 10; i++)
{
cout << "\n\n\tPlease enter the name of contestant number " << num[i] << ": ";
cin >> names[i];
cout << names[i];
cout << "\n\tPlease enter the time it took for them to complete the Crawl style: ";
cin >> times[i];
cout<<times[i];
while (!cin)
{
cout << "\n\tError! Please enter a valid time: ";
cin.clear();
cin.ignore();
cin >> times[i];
}
if(times[i]==times[min1]){
if(times[min1]==times[min2]){
min3=i;
}else{min2 =i;}
}else if(times[i]==times[min2]){
min3=i;
}
if (times[i] < times[min1]){
min1 = i;
cout <<i;
}
int j=0;
while(j<i){
if((times[j]>times[min1])&&(times[j]<times[min2])){
min2 =j;
j++;
}
j++;
}
m=0;
while(m<i){
if((times[m]>times[min2])&&(times[m]<times[min3])){
min3 =m;
m++;
}
m++;
}
cout << "\n\n\t----------------------------------------------------------------------";
}
cout << "\n\n\tThe top three winners of the Crawl style race are as follows";
cout << "\n\n\t1st Place - " << names[min1];
cout << "\n\n\t2nd Place - " << names[min2];
cout << "\n\n\t3rd Place - " << names[min3];
return 0;
}
There is actually an algorithm in the standard library that does exactly what you need: std::partial_sort. Like others have pointed out before, to use it you need to put all the participant data into a single struct, though.
So start by defining a struct that contains all relevant data. Since it seems to me that you only use the number of the contestants in order to be able to later find the name to the swimmer with the fastest time, I'd get rid of it. Of course you could also add it back in if you like.
struct Swimmer {
int time;
std::string name;
};
Since you know that there always will be exactly 10 participants in a race, you can also go ahead and replace the C-style array by a std::array.
The code to read in the users then could look like this:
std::array<Swimmer, 10> participants;
for (auto& participant : participants) {
std::cout << "\n\n\tPlease enter the name of the next contestant: ";
std::cin >> participant.name;
std::cout << "\n\tPlease enter the time it took for them to complete the Crawl style: ";
while(true) {
if (std::cin >> participant.time) {
break;
}
std::cout << "\n\tError! Please enter a valid time: ";
std::cin.clear();
std::cin.ignore();
}
std::cout << "\n\n\t----------------------------------------------------------------------";
}
Partial sorting is now essentially a one-liner:
std::partial_sort(std::begin(participants),
std::begin(participants) + 3,
std::end(participants),
[] (auto const& p1, auto const& p2) { return p1.time < p2.time; });
Finally you can simply output the names of the first three participants in the array:
std::cout << "\n\n\tThe top three winners of the Crawl style race are as follows";
std::cout << "\n\n\t1st Place - " << participants[0].name;
std::cout << "\n\n\t2nd Place - " << participants[1].name;
std::cout << "\n\n\t3rd Place - " << participants[2].name << std::endl;
The full working code can be found on coliru.
This is not a full solution to your problem, but just meant to point you into the right direction...
#include <iostream>
#include <limits>
#include <algorithm>
using namespace std;
template <int N>
struct RememberNsmallest {
int a[N];
RememberNsmallest() { std::fill_n(a,N,std::numeric_limits<int>::max()); }
void operator()(int x){
int smallerThan = -1;
for (int i=0;i<N;i++){
if (x < a[i]) { smallerThan = i; break;}
}
if (smallerThan == -1) return;
for (int i=N-1;i>smallerThan;i--){ a[i] = a[i-1]; }
a[smallerThan] = x;
}
};
int main() {
int a[] = { 3, 5, 123, 0 ,-123, 1000};
RememberNsmallest<3> rns;
rns = std::for_each(a,a+6,rns);
std::cout << rns.a[0] << " " << rns.a[1] << " " << rns.a[2] << std::endl;
// your code goes here
return 0;
}
This will print
-123 0 3
As you need to know also the names for the best times, you should use a
struct TimeAndName {
int time;
std::string name;
}
And change the above functor to take a TimeAndName instead of the int and make it also remember the names... or come up with a different solution ;), but in any case you should use a struct similar to TimeAndName.
As your array is rather small, you could even consider to use a std::vector<TimeAndName> and sort it via std::sort by using your custom TimeAndName::operator<.
I'm currently working on a program that outputs the number 1089 (i.e the Magic Number) of a three digit integer who's first digit is greater than its last. I have some code typed up, but am not receiving 1089, instead I'm receiving 891. Could anyone offer some explanation as to why.
//Uses a cout to inform user will be using the number 412 as an example.
//Uses a cout to explain to user the number needs to be reversed.
cout << "Alright, let's walk through an example, using the number 412." << endl;
int numExample = 412;
cout << "Please input 412" << endl;
cin >> numExample;
cout << "First, the number 412 is reversed." << endl;
//The following is done for reversing the number 412:
int reverseNum = 0, remainder = 0;
while (numExample)
{
remainder = numExample % 10;
reverseNum = (reverseNum * 10) + remainder;
numExample = numExample / 10;
}
cout << "The reverse of 412 is " << reverseNum << endl;
cout << "Next, we want to subtract the reverse of the original number from its reverse" << endl;
cout << "This gives us 198" << endl;
cout << "From there, we want to reverse 198." << endl;
//The same procedure is used to reverse 198
int numExample2 = 198;
cout << "Please enter 198" << endl;
cin >> numExample2;
int reverseNum2 = 0, remainder2 = 0;
while (numExample2)
{
remainder2 = numExample2 % 10;
reverseNum2 = (reverseNum2 * 10) + remainder2;
numExample2 = numExample2 / 10;
}
cout << "The reverse of 198 is " << reverseNum2 << endl;
int magicNumber = (reverseNum2 + numExample2);
cout << "Following that, we want to add 891 to 189 which gives us " << magicNumber << endl;
Try writing a function to handle this so your code is cleaner (It will also make it easier for people to help you!)
#include <iostream>
#include <cmath>
using namespace std;
int reverseDigit(int num); // For example purposes
int _tmain(int argc, _TCHAR* argv[])
{
int Number1,
Number2,
temp1,
temp2,
Result;
cout << "Enter the number 412: ";
cin >> Number1;
temp1 = reverseDigit(Number1);
temp1 = Number1 - temp1;
cout << "Enter the number 198: ";
cin >> Number2;
temp2 = reverseDigit(Number2);
Result = temp1 + temp2;
cout << "The magic number is: " << Result << endl;
return 0;
}
int reverseDigit(int num)
{
int reverseNum = 0;
bool isNegative = false;
if (num < 0)
{
num = -num;
isNegative = true;
}
while (num > 0)
{
reverseNum = reverseNum * 10 + num % 10;
num = num / 10;
}
if (isNegative)
{
reverseNum = -reverseNum;
}
return reverseNum;
}
I realize you're not working with negatives so you can remove that bit if you chose to use this, you can also expand on it... That being said this will make the actual " Reversing process " easier to work with and improve upon and read.
Using C++ to figure out the factorial is straightforward enough. To print the values coming up (if factorial is 5) ... 1 * 2, * 3, * 4 * 5 also no problem - as I think I've done below.
But what I'm having a hard time doing is saying show me 5 * 4 then value * 3 then value * 2 etc. I want to be able to print the data going down and I can't seem to figure it out.
#include <iostream>
using namespace std;
int factorial(int n);
int main()
{
int number;
cout << "Enter an integer value ";
cin >> number;
cout << "The factorial of " << number << " is ";
cout << factorial(number) << endl;
}
int factorial(int n)
{
if (n == 0)
return 1; // Base case
else
{
n = n * factorial(n - 1); // Recursive case
cout << " going up" << n << " ";
return n;
}
}
There are a couple of other posts but I didn't find one asking the same thing.
The desired results are: 20 60 120
The current results are 1 2 6 24 120
Please advise.
Thank you.
Just change where you are printing the value
else
{
n = n * factorial(n - 1); // Recursive case
cout << " going up" << n << " ";
return n;
}
to
else
{
cout << " going down" << n << " ";
n = n * factorial(n - 1); // Recursive case
return n;
}
The above would print 5 4 3 2 1 but if you want something like
5 20 60 ...
Than you have to change the recursive definition a bit.
#include<iostream>
using namespace std;
int factorial(int n,int temp);
int main()
{
int number;
cout << "Enter an integer value ";
cin >> number;
cout << "The factorial of " << number << " is ";
cout << factorial(number,1) << endl;
}
int factorial(int n,int temp)
{
if (n == 0)
return temp; // Base case
else
{
cout << " going down" << n * temp << " ";
factorial(n - 1,n*temp); // Recursive case
//return n;
}
}
I am making a clock-driven simulation program and, among other issues, my main while loop, while(jobsCompleted < jobsToComplete) is looping more times than expected/wanted. For example, if I were to assign 500 to jobsToComplete, the output at the end of the program would tell me that there were 505 jobs completed. I have tried to debug this one issue for at least an hour now, but to no avail. Any help is appreciated. Thanks!
#include <iostream>
#include <string>
#include <stdlib.h>
#include <queue>
#include <fstream>
#include "job.cpp"
using namespace std;
int main()
{
ofstream cpuSim;
cpuSim.open("cpuSim.out.txt");
int clock = 0, jobsCompleted = 0, jobsToComplete = 0, probUser = 0, probability, id = 0;
jobType_t job_type;
int inWQ, outWQ, inCPUQ, outCPUQ, required, given, jobTypeInt, timeSpentInCPUqueue = 0, timeSpentInWaitQueue = 0, CPUidle = 0;
queue<job> CPUqueue, waitQueue;
int numIO = 0, numCPU = 0;
srand(time(NULL));
cout << "Enter how many jobs need to be completed: ";
cin >> jobsToComplete;
cout << endl << "Enter the probability that a new job is created: ";
cin >> probUser;
cout << endl;
while(jobsCompleted < jobsToComplete)
{
clock++;
probability = rand() % 100 + 1;
if(probability > probUser)
{
for(int i=0; i<jobsToComplete; i++)
{
id = rand() % 1000 + 1;
jobTypeInt = rand() % 100 + 1;
if(jobTypeInt >= 50)
job_type = IO_bound;
else
job_type = CPU_bound;
required = rand() % 10;
job *newJob = new job(id, job_type, inWQ, outWQ, inCPUQ, outCPUQ, required, given);
waitQueue.push(*newJob);
}
while((CPUqueue.size() <= 10) && waitQueue.empty() == false)
{
waitQueue.front();
job temp = waitQueue.back();
waitQueue.pop();
temp.setTimeExitedWQueue(clock);
temp.setTimeEnteredCPUQueue(clock);
CPUqueue.push(temp);
}
double oneSecond = 1.0, timeSpent = 0;
while((oneSecond > 0.0) && (!CPUqueue.empty()))
{
job top = CPUqueue.front();
CPUqueue.pop();
if(top.getJobType() == IO_bound)
{
top.setTimeGiven(top.getTimeGiven() + .1);
timeSpent = .1;
numIO++;
}
else
{
top.setTimeGiven(top.getTimeGiven() + .2);
timeSpent = .2;
numCPU++;
}
if(top.getTimeRequired() <= top.getTimeGiven())
{
top.setTimeExitedCPUQueue(clock);
jobsCompleted++;
timeSpentInWaitQueue += (top.getTimeExitedWQueue() - top.getTimeEnteredWQueue());
timeSpentInCPUqueue += (top.getTimeExitedCPUQueue() - top.getTimeEnteredCPUQueue());
}
else
CPUqueue.push(top);
oneSecond -= timeSpent;
if((clock%60 == 0) && (clock > 600)) //every 60 seconds after the first 10 minutes
{
cout << "After the first 10 minutes:" << endl;
cout << "Time: " << clock << endl;
cout << "Number of jobs in the wait queue: " << waitQueue.size() << endl;
cout << "Number of jobs in the CPU queue: " << CPUqueue.size() << endl;
job temp1 = waitQueue.front();
job temp2 = CPUqueue.front();
cout << "Job number of front wait job: " << temp1.getID() << endl;
cout << "Job number of front CPU job: " << temp2.getID() << endl;
}
else
{
cout << "Job Number: " << jobsCompleted << endl;
cout << "Job ID: " << top.getID() << endl;
cout << "Job Type: " << top.getJobType() << endl;
cout << "Time in CPU Queue: " << timeSpentInCPUqueue << endl;
cout << "Time Entered CPU Queue: " << top.getTimeEnteredCPUQueue() << endl << endl;
}
}
if((oneSecond > 0) && (CPUqueue.empty()))
CPUidle += oneSecond;
}
}
cout << "I/O_bound jobs: " << numIO << endl;
cout << "CPU_bound jobs: " << numCPU << endl;
cout << "*****JOBS COMPLETED: " << jobsCompleted << " *****" << endl << endl;
return 0;
}
And as a less pertinent question, I cannot get my enumerated data types to print out correctly nor my IDs at the very begging to pass into *newJob correctly...
Let's say it's been looping for a while and now jobsCompleted is 499 (and your jobsToComplete is 500). Okay, so this is the last loop right? Yes! But the incrementing of jobsCompleted happens within another nested while loop. So if that nested loop occurs 6 times, jobsCompleted will be 505 and then the outer while loop will end, leaving you with a total number of jobs completed at 505.
Telling you how to fix it would require understanding the logic of your code, but there's a bit too much for me to figure out. Maybe this will help you.
By looking at the code it's clear that this happens because you have a situation like the following
while (x < y) {
...
while (condition) {
...
if (condition) {
++x;
}
}
}
This means that for every outer iteration it may happen that you are incrementing x more than once, so you enter the last iteration (x == 499) and then increment it 6 times while inside the inner loop. You should debug that part of code to understand why it happens, explicitly you should check these two conditions:
while((oneSecond > 0.0) && (!CPUqueue.empty()))
if(top.getTimeRequired() <= top.getTimeGiven())
because on last iteration the are both true at least 6 times.