
Recursive Football Problem
By: a guest on
May 17th, 2012 | syntax:
C++ | size: 2.15 KB | hits: 56 | expires: Never
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <stdio.h>
using namespace std;
struct Node
{
vector<Node> nodes;
string score;
};
struct Score
{
int value;
string str;
};
bool getAllScores(int score, Node *top);
void printScores(Node *top, string builder);
Score allScores[] =
{
{ 2, "Safety" },
{ 3, "FieldGoal" },
{ 6, "Touchdown" },
{ 7, "Touchdown w/ Extra Point" },
{ 8, "Touchdown w/ 2 Point Conversion" }
};
int main()
{
Node top;
// show the welcome message, and ask for input
printf("Welcome to Adam's sick football program!\n\n" \
"This program will display all the possible ways to get a certain football score.\n\n" \
"What score would you like to see? ");
// read the score input
int score;
scanf("%d", &score);
if (score < 2)
{
printf("\nScore must be at least 2!\n");
// freeze the program, so it doesn't close
scanf("%c", &score);
scanf("%c", &score);
return 0;
}
printf("\n");
// get all of the scores, and then print them out
getAllScores(score, &top);
printScores(&top, "");
// freeze the program, so it doesn't close
scanf("%c", &score);
scanf("%c", &score);
return 0;
}
bool getAllScores(int score, Node *top)
{
if (score == 0)
return true;
else if (score <= 1)
return false;
// loop through all the possible football scores
for (int i = 0; i < 5; i++)
{
// create a new node with the string being the score
Node n;
n.score = allScores[i].str;
// if the score will work, then add the node into the tree
if (getAllScores(score - allScores[i].value, &n))
top->nodes.push_back(n);
}
return true;
}
void printScores(Node *top, string builder)
{
// for some reason VS was saying that you can't use the '+' operator
// to concatenate strings so I had to use append instead, it LIES
if (top->nodes.size() == 0)
{
string temp = builder;
temp.append(top->score);
printf("%s\n", temp.c_str());
}
for (int i = 0; i < top->nodes.size(); i++)
{
string temp = builder;
temp.append(top->score);
temp.append(" ");
printScores(&top->nodes.at(i), temp);
}
}