Recursion In a General Tree [closed] - c++

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I've created a general tree based on a Node class that has 2 pointers: next points to the node's first son , bros points to the next brother of the node.
Each node has a capacity (int) and each leaf is considered one unit of demand , the goal is to say weather or not the tree supports the demand (meaning each branch of the tree has enough capacity to supply all of the demand).
The tree building part works quite nicely but it seems there's a bug i'm missing in my supplier and recursion function. general explanation:
isSupplier(node) - checks that the node has enough capacity to support all leafs under its branch.
canDemandBeAnswered(node) - recursive function that is supposed to call isSupplier for all nodes starting with the leafs going upward.
problem is that after the recursion encounters the first leaf it gets stuck on an unknown node (at height 1 with zero sons which is impossible because if the node is a leaf the recursion isn't called!)
Hopefully someone can find something i missed , thank you!
// This method checks if this node can supply all of its leafs.
bool isSupplier()
{
if ( this->isLeaf() ) { return 1;}
else
{
this->num_of_leafs = this->Count_Leafs();
Node* iter = this->next;
while ( (iter != NULL) )
{
if ( iter->isLeaf() == 0 )
{ this->num_of_leafs += iter->num_of_leafs; }
iter = iter->bros;
}
}
if (this->capacity < this->num_of_leafs) { return 0; }
else { return 1; }
}
bool canDemandBeAnswered(Node* root)
{
cout << "Height: " << root->getHeight() << " , sons: " << root->Count_Sons() << " ,bros: " << root->getNumBros() << " ,leafs: " << root->getNumLeafs() << " \n";
if ( root->isLeaf() ) { return 1; }
Node* iter = root->next;
while ( iter != NULL )
{
canDemandBeAnswered(iter);
iter->getNextBro();
}
return root->isSupplier();
};
The tree creation and recursive call:
Node* s8 = new Node(8);
Node* s5 = new Node(5);
Node* s6 = new Node(6);
for(int i=0; i < 2 ; i++){
s6->addChild(new Node());
}
Node* s7 = new Node(7);
Node* s2 = new Node(2);
for(int i=0; i < 3 ; i++){
s2->addChild(new Node());
}
Node* s3 = new Node(3);
Node* s2_2 = new Node(2);
s2_2->addChild(new Node());
Node* s4 = new Node(4);
for(int i=0; i < 5 ; i++){
s4->addChild(new Node());
}
Node* s1 = new Node(1);
for(int i=0; i < 2 ; i++){
s1->addChild(new Node());
}
Node* s2_3 = new Node(2);
for(int i=0; i < 4 ; i++){
s2_3->addChild(new Node());
}
Node* s2_4 = new Node(2);
for(int i=0; i < 3 ; i++){
s2_4->addChild(new Node());
}
s8->addChild(s5);
s8->addChild(s6);
s5->addChild(s7);
s5->addChild(s2);
s6->addChild(s3);
s6->addChild(s2_2);
s7->addChild(s4);
s7->addChild(s1);
s3->addChild(s2_3);
s3->addChild(s2_4);
cout << "s8 height: " << s8->getHeight() << " , sons: " << s8->Count_Sons() << " , bros: " << s8->getNumBros() << " , num of leaf: " << s8->getNumLeafs() << " \n";
cout << "s5 height: " << s5->getHeight() << " , sons: " << s5->Count_Sons() << " , bros: " << s5->getNumBros() << " , num of leaf: " << s5->getNumLeafs() << " \n";
cout << "s6 height: " << s6->getHeight() << " , sons: " << s6->Count_Sons() << " , bros: " << s6->getNumBros() << " , num of leaf: " << s6->getNumLeafs() << " \n";
cout << "s7 height: " << s7->getHeight() << " , sons: " << s7->Count_Sons() << " , bros: " << s7->getNumBros() << " , num of leaf: " << s7->getNumLeafs() << " \n";
cout << "s2 height: " << s2->getHeight() << " , sons: " << s2->Count_Sons() << " , bros: " << s2->getNumBros() << " , num of leaf: " << s2->getNumLeafs() << " \n";
cout << "s3 height: " << s3->getHeight() << " , sons: " << s3->Count_Sons() << " , bros: " << s3->getNumBros() << " , num of leaf: " << s3->getNumLeafs() << " \n";
cout << "s2_2 height: " << s2_2->getHeight() << " , sons: " << s2_2->Count_Sons() << " , bros: " << s2_2->getNumBros() << " , num of leaf: " << s2_2->getNumLeafs() << " \n";
cout << "s4 height: " << s4->getHeight() << " , sons: " << s4->Count_Sons() << " , bros: " << s4->getNumBros() << " , num of leaf: " << s4->getNumLeafs() << " \n";
cout << "s1 height: " << s1->getHeight() << " , sons: " << s1->Count_Sons() << " , bros: " << s1->getNumBros() << " , num of leaf: " << s1->getNumLeafs() << " \n";
cout << "s2_3 height: " << s2_3->getHeight() << " , sons: " << s2_3->Count_Sons() << " , bros: " << s2_3->getNumBros() << " , num of leaf: " << s2_3->getNumLeafs() << " \n";
cout << "s2_4 height: " << s2_4->getHeight() << " , sons: " << s2_4->Count_Sons() << " , bros: " << s2_4->getNumBros() << " , num of leaf: " << s2_4->getNumLeafs() << " \n";
bool ans = hw4->canDemandBeAnswered(s8);
and the big finale , my debug output:

Your loop
while (iter != NULL)
{
canDemandBeAnswered(iter);
iter->getNextBro();
}
doesn't do anything since you never modify iter.
I suspect you meant to say
iter = iter->getNextBro();
You're also ignoring the return value of the recursive call, which is probably not what you intended, but it's not entirely clear what it's supposed to do.

Related

Football tournament with matrix

I'm trying to make a football tournament in C++, in which the user inputs the name of the teams(8 teams) and then each team has to play with the other one 1 time. Firstly, I don't know how to read the team names, I mean I tried to use .getline or just cin of a char array, but then I need to put the teams into the matrix and after the final game my program should print the table. So there's the first question: how to read the names and basically make the program think they are numbers or does it work with just with names, no need to use int? And then the users inputs the result for every game, but here comes the hard part. After all the results have been introduced, the matrix rotates cyclic and then the result stored in the variables(you will see in code victory/losses) overwrites themselves, so at the end, I cannot print the right table. So that's the second question: How can I make them store to the right 'team' while they rotate? Sorry if I didn't quite explain very well how it works, hope you understand it. Cheers!
// FOOTBALL TOURNAMENT
int map[2][4];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
cout << "map[" << i << "][" << j << "]= ";
cin >> map[i][j];
}
}
cout << "The map looks like this:" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
cout << map[i][j] << " ";
}
cout << endl;
}
map[0][0] = 1;
int temp = 0, temp2 = 0, temp3 = 0, temp4 = 0, temp5 = 0, temp6 = 0;
int a, b, c, d, e, f, g, h, round = 0;
int victory_m00(0), losses_m10(0), victory_m10(0), losses_m00(0), victory_m01(0), losses_m11(0), victory_m11(0), losses_m01(0);
int victory_m02(0), losses_m12(0), victory_m12(0), losses_m02(0), victory_m03(0), losses_m13(0), victory_m13(0), losses_m03(0);
do
{
// Insert result for every game
cout << "Enter the result of the first game between " << map[0][0] << " vs. " << map[1][0] << endl;
cin >> a >> b;
if (a > b) {
victory_m00++;
losses_m10++;
}
else if (a < b)
{
victory_m10++;
losses_m00++;
}
cout << "Enter the result of the first game between: " << map[0][1] << " vs. " << map[1][1] << endl;
cin >> c >> d;
if (c > d) {
victory_m01++;
losses_m11++;
}
else if (c < d)
{
victory_m11++;
losses_m01++;
}
cout << "Enter the result of the first game between: " << map[0][2] << " vs. " << map[1][2] << endl;
cin >> e >> f;
if (e > f) {
victory_m02++;
losses_m12++;
}
else if (e < f)
{
victory_m12++;
losses_m02++;
}
cout << "Enter the result of the first game between: " << map[0][3] << " vs. " << map[1][3] << endl;
cin >> g >> h;
if (g > h) {
victory_m03++;
losses_m13++;
}
else if (g < h)
{
victory_m13++;
losses_m03++;
}
round++;
// Map switching
temp = map[1][0];
map[1][0] = map[0][1];
temp2 = map[1][1];
map[1][1] = temp;
temp3 = map[1][2];
map[1][2] = temp2;
temp4 = map[1][3];
map[1][3] = temp3;
temp5 = map[0][3];
map[0][3] = temp4;
temp6 = map[0][2];
map[0][2] = temp5;
map[0][1] = temp6;
// Table calculating and printing ~ also this has to be outside the loop (but at first i wanted to print the table after every 'round'
cout << "This is how the table looks like after the " << round << " round: \n";
cout << map[0][0] << " has: " << victory_m00 << " victory(-ies) and " << losses_m00 << " loss-es!\n";
cout << map[0][1] << " has: " << victory_m01 << " victory(-ies) and " << losses_m01 << " loss-es!\n";
cout << map[0][2] << " has: " << victory_m02 << " victory(-ies) and " << losses_m02 << " loss-es!\n";
cout << map[0][3] << " has: " << victory_m03 << " victory(-ies) and " << losses_m03 << " loss-es!\n";
cout << map[1][0] << " has: " << victory_m10 << " victory(-ies) and " << losses_m10 << " loss-es!\n";
cout << map[1][1] << " has: " << victory_m11 << " victory(-ies) and " << losses_m11 << " loss-es!\n";
cout << map[1][2] << " has: " << victory_m12 << " victory(-ies) and " << losses_m12 << " loss-es!\n";
cout << map[1][3] << " has: " << victory_m13 << " victory(-ies) and " << losses_m13 << " loss-es!\n";
cout << endl;
cout << endl;
} while (map[0][1] != 2);
```

How can I do a recursive print using class linked list

//PROTOYPE
void Display();
//CALL
list.Display();
/***********************************
* Print the contents of the list *
***********************************/
void EmployeeList::Display()
{
// Temporary pointer
newEmployee * tmp;
tmp = head;
// No employees in the list
if(tmp == NULL )
{
cout << "\n\n\t\t***THERE IS NO EMPLOYEE INFORMATION STORED YET***\n";
return;
}
cout << "\n\n"
<< "\t\t************************************************\n"
<< "\t\t* Employee IDs and Yearly Salary DataBase *\n"
<< "\t\t************************************************\n\n";
cout << "\t\t\tEmployee IDs" << setw(20) << right << "Yearly Salaries\n";
// One employee in the list
if(tmp->Next() == NULL )
{
cout << "\t\t\t " << tmp->empID() << setw(13) << right << " "
<< "$" << setw(2) << tmp->ySalary() << endl;
}
else
{
do
{
cout << "\t\t\t " << tmp->empID() << setw(13) << " "
<< right << "$" << setw(2) << tmp->ySalary() << endl;
tmp = tmp->Next();
}while(tmp != NULL );
cout << "\n\t\t\t ***Thank You***" << endl;
}
}
I need help on what to write in order to do a recursive function call for Display function.
I need to display the list in reverse order from last to first.
How can I do a recursive print using class linked list?
I am going to assume that your list nodes do not have a Previous() method (otherwise a reverse print loop would have been trivial to implement without using recursion).
Try something like this:
void DisplayEmployeeInReverseOrder(newEmployee * emp)
{
if (emp->Next() != NULL)
DisplayEmployeeInReverseOrder(emp->Next());
cout << "\t\t\t " << emp->empID() << setw(13) << right << " "
<< "$" << setw(2) << emp->ySalary() << endl;
}
void EmployeeList::Display()
{
// Temporary pointer
newEmployee * tmp;
tmp = head;
// No employees in the list
if(tmp == NULL )
{
cout << "\n\n\t\t***THERE IS NO EMPLOYEE INFORMATION STORED YET***\n";
return;
}
cout << "\n\n"
<< "\t\t************************************************\n"
<< "\t\t* Employee IDs and Yearly Salary DataBase *\n"
<< "\t\t************************************************\n\n";
cout << "\t\t\tEmployee IDs" << setw(20) << right << "Yearly Salaries\n";
DisplayEmployeeInReverseOrder(tmp);
cout << "\n\t\t\t ***Thank You***" << endl;
}

C++ array beginner

I have this code that I have been working on for fun, it is as basic as it gets, becuase I am a beginner, and it works fine, but I can't seem to be able to figure out how to make it show the least and the most amount of pancakes ate. Thank you a lot in advance.
#include <iostream>
using namespace std;
int main(){
int pancakes[10];
int x,i;
cout << "Hello user!" << endl;
cout << endl;
cout << "Please enter how many pancakes did each of the 10 people eat:" << endl;
cout << endl;
for (i=0;i<10;i++ ){
cin >> x;
pancakes[i]=x;
}
cout << "1st person ate" << " " << pancakes[0] << " " << "pancakes" << endl;
cout << "2nd person ate" << " " << pancakes[1] << " " << "pancakes" << endl;
cout << "3rd person ate" << " " << pancakes[2] << " " << "pancakes" << endl;
cout << "4th person ate" << " " << pancakes[3] << " " << "pancakes" << endl;
cout << "5th person ate" << " " << pancakes[4] << " " << "pancakes" << endl;
cout << "6th person ate" << " " << pancakes[5] << " " << "pancakes" << endl;
cout << "7th person ate" << " " << pancakes[6] << " " << "pancakes" << endl;
cout << "8th person ate" << " " << pancakes[7] << " " << "pancakes" << endl;
cout << "9th person ate" << " " << pancakes[8] << " " << "pancakes" << endl;
cout << "10th person ate" << " " << pancakes[9] << " " << "pancakes" << endl;
return 0;
}
Since you are a beginner, I will put a simple solution using a loop.
int max = 0;
for(i = 0; i < 10; i++) {
if(pancakes[i] > max) max = pancakes[i];
}
cout << "Most amount of pancakes eaten by a single person: " << max << endl;
You can use min_element and max_element from the standard library to do this:
#include <algorithm>
cout << "The smallest number of pancakes was " << *min_element(pancakes, pancakes + 10) << endl;
cout << "The largest number of pancakes was " << *max_element(pancakes, pancakes + 10) << endl;
Firstly, instead of having around 10 cout's, you can use a loop to print them :
for (i=0;i<10;i++ ){
if(i==0)
cout <<i+1<< "st person ate" << " " << pancakes[i] << " " << "pancakes" << endl;
else if(i==1)
cout << i+1<<"nd person ate" << " " << pancakes[i] << " " << "pancakes" << endl;
else if(i==2)
cout << i+1<<"rd person ate" << " " << pancakes[i] << " " << "pancakes" << endl;
else
cout <<i+1<< "th person ate" << " " << pancakes[i] << " " << "pancakes" << endl;
}
Secondly, you can directly enter values into your array, no need for an intermediate variable x:
for (i=0;i<10;i++ ){
cin >> pancakes[i];
}
For your max and min problem, take two variables, say - max and min. Initialise them to any arbitrary smallest (say 0, if you are not dealing with negative numbers) and largest value (say, INT_MAX) respectively. Alternatively, you can initialise them to the first element of your array.
For finding max and min, you can traverse the entire array, while checking if the elements are greater or lesser than your max and min variables. If they are, then assign them to your variables:
for (i=0;i<10;i++ ){
if(pancakes[i]>max)
max = pancakes[i];
if(pancakes[i]<min)
min = pancakes[i];
}
You can add std::cout inside for loop like below,
for (int i = 0; i < 10; i++ )
{
std::cin >> pancakes[i];
std::cout << i+1 <<"st person ate" << " " << pancakes[i] << " " << "pancakes" << std::endl;
}
int maxpancakes = pancakes[0];
int minpancakes = pancakes[0];
for(int i = 0; i < pancakes.length(); i++ )
{
if( pancakes[i] < minpancakes )
minpancakes = pancakes[i];
if( pancakes[i] > maxpancakes )
maxpancakes = pancakes[i];
}
std::cout << "The smallest pan cake had is :" << minpancakes << std::endl;
std::cout << "The max pan cake had is :" << maxpancakes << std::endl;

trying to order 3 values from least to greatest C++

I have a program that takes numbers that a person enters and sums it.
This happens 3 times, so I have 3 totals. The problem I am having is that I need to order them from greatest to least no matter what the sums come out to be.(this isnt the full code assume the sums are calculated and are declared)
#include <iostream>
#include <string>
using namespace std;
string firstName1, lastName1; // input and output for the users names
string firstName2, lastName2;
string firstName3, lastName3;
// from greatest to least
if ( sum > sum_2 > sum_3 )
{
cout << "Total for" << " " << firstName1 << " " << lastName1 << " " << "$" << sum << ".00" << endl;
cout << "Total for" << " " << firstName2 << " " << lastName2 << " " << "$" << sum_2 << ".00" << endl;
cout << "Total for" << " " << firstName3 << " " << lastName3 << " " << "$" << sum_3 << ".00" << endl;
}
In c++, the syntax sum > sum_2 > sum_3 won't evaluate as you're assuming. It's equivalent to (sum > sum_2) > sum_3.
In the case where sum is greater than sum_2, sum > sum_2 will evaluate to true. Then, this boolean value will be converted to an integer, 1 and compared with sum_3.
To do what you're trying to accomplish try:
if (sum > sum_2 && sum_2 > sum_3)
Use a helper swap function:
void swap( int *a, int *b )
{
int temp = *a;
*a = *b;
*b = temp;
}
And bubble sort it:
int sums[3] = { sum, sum_2, sum_3 };
for ( int i = 0; i < 3; ++i )
for ( int j = 0; j < i; ++j )
if ( sums[j] < sums[i] )
swap( &sums[j], &sums[i] );
cout << "Total for" << " " << firstName1 << " " << lastName1 << " " << "$" << sums[0] << ".00" << endl;
cout << "Total for" << " " << firstName2 << " " << lastName2 << " " << "$" << sums[1] << ".00" << endl;
cout << "Total for" << " " << firstName3 << " " << lastName3 << " " << "$" << sums[2] << ".00" << endl;

How to make an array print zeros when there is no input in that slot

The user inputs a double and string which gets stored into two arrays. Like so :
{
double DoC;
string Nm;
cout << " Please enter the amount charged to your credit card " << endl;
cin >> DoC;
cout << " Please enter where the charge was made " << endl;
cin >> Nm;
getline(cin, Nm);
cca.doCharge(Nm,DoC);
break;
}
Then the double and string are passed to this :
{
if (amount > 0)
{
for (int i = 9; i != 0; i--)
{
last10withdraws[i] = last10withdraws[i-1];
last10charges[i] = last10charges[i-1];
}
last10withdraws[0] = amount;
last10charges[0] = name;
setBalanceW(amount);
}
else
{
cout << " ERROR. Number must be greater then zero. " << endl;
}
return 0;
}
This seems to work very well for storing the data into the arrays. However I then use this function to display the data inside of the arrays :
{
cout << " Account: Creditcard Withdraws " << " " << " Account: Creditcard Deposits " << " " << " Account: Creditcard last 10 charges " << endl;
cout << " " << last10withdraws[0] << " " << last10deposits[0] << " " << last10charges[0] << endl;
cout << " " << last10withdraws[1] << " " << last10deposits[1] << " " << last10charges[1] << endl;
cout << " " << last10withdraws[2] << " " << last10deposits[2] << " " << last10charges[2] << endl;
cout << " " << last10withdraws[3] << " " << last10deposits[3] << " " << last10charges[3] << endl;
cout << " " << last10withdraws[4] << " " << last10deposits[4] << " " << last10charges[4] << endl;
cout << " " << last10withdraws[5] << " " << last10deposits[5] << " " << last10charges[5] << endl;
cout << " " << last10withdraws[6] << " " << last10deposits[6] << " " << last10charges[6] << endl;
cout << " " << last10withdraws[7] << " " << last10deposits[7] << " " << last10charges[7] << endl;
cout << " " << last10withdraws[8] << " " << last10deposits[8] << " " << last10charges[8] << endl;
cout << " " << last10withdraws[9] << " " << last10deposits[9] << " " << last10charges[9] << endl;
cout << endl;
}
Lets say the user has inputted three doubles into the deposit array. When I call the function to display it I get something like this :
60
30
20
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
-9.25596e+061
How can I make it so that the -9.25596e+061's are 0's? I have not been able to find anything really helping me. Also with the array that contains strings, when it is called to display it displays nothing. Why is this ?
Initialize the array as:
int last10withdraws[10] = {0};
Now all elements are zero.
If the user enters three numbers, then first three elements will be non-zero (assuming only non-zero is allowed), and the rest will be zero.
If last10withdraws is a member of a class m(and you're using C++03), then you can use member-initializer list to default-initialize which will initialize all the elements to zero.
class myclass
{
int last10withdraws[10];
public:
myclass() : last10withdraws()
{ //^^^^^^^^^^^^^^^^^^^ member initializer list
}
};
Hope that helps.
You are getting the error because you are not initializing the values. Start by saying int last10withdraws[10] = {0}; That will initialize all values to zero.