Question

In: Computer Science

c++ Create a class named EvolutionTree which will hold a list of species and their expected...

c++

Create a class named EvolutionTree which will hold a list of species and their expected age, and allow a user to search for a particular species or an age.


EvolutionTree should have private data members:

  • species (a string array of size 400 with all the species)
  • speciesAges (an int array of size 400 for all the species' ages).

EvolutionTree should have a default constructor which should initialize the species array to empty strings ("") and initialize the speciesAges array to 0's and the following public methods:

  • int LoadTree(string filename)
  • int SearchForSpecies(string speciesName)
  • string GetSpecies(int speciesAge)

LoadTree should read in a filename where each line is the name of a species and its expected age, separated by a comma. The method should read the file and put the appropriate data into species and speciesAges. LoadTree should return -1 for invalid filenames, and it should return 0 for valid filenames. Each species and species age will only appear once. The last line may or may not end in '\n'.

Few lines from the file to be loaded:

Human,82
Asian elephants,86
Dog,7
Cat,10

SearchForSpecies will search for a particular species' name, and return the index where that name is located. It should return -1 if the name is not found.

GetSpecies will take in an age and return the corresponding species name. It should return an empty string ("") if the age is not found.

You only need to write the class definition and any code that is required for that class. Place all code within the class definition. Our code will create and test your class.

NOTE: We have provided a function that may make the parsing easier:
      int split(string s, char sep, string words[], int max_words);

int split(string phrase, char delimer, string result[], int length)
{
//add one more delimer in the end
phrase += delimer;
//introduce variables
string partHolder = "";
int partCounter = 0;
int phraseLength = phrase.length();
for (int i = 0; i < phraseLength; i++)
{
//if we do not need to split,
if (phrase[i] != delimer)
{
//store result in the correct position
partHolder += phrase[i];
}
else
{
//make postion and holder ready for a new word, store part in result string, and count a part
if (partCounter < length && partHolder != "") //accounts for double delimer
{
result[partCounter] = partHolder;
partCounter++;
partHolder = "";
}
}
}

C++

Solutions

Expert Solution

Screenshot

Program

/*
Program to search a species with name and age
Here species details store as class attribute
Method of class use for species search
*/
#include <iostream>
#include<string>
#include<fstream>
using namespace std;
#define MAX_SIZE 400
class EvolutionTree {
   //Attributes
private:
   string species[MAX_SIZE];
   int speciesAges[MAX_SIZE];
   int split(string phrase, char delimer, string result[], int length)
   {
       //add one more delimer in the end
       phrase += delimer;
       //introduce variables
       string partHolder = "";
       int partCounter = 0;
       int phraseLength = phrase.length();
       for (int i = 0; i < phraseLength; i++)
       {
           //if we do not need to split,
           if (phrase[i] != delimer)
           {
               //store result in the correct position
               partHolder += phrase[i];
           }
           else
           {
               //make postion and holder ready for a new word, store part in result string, and count a part
               if (partCounter < length && partHolder != "") //accounts for double delimer
               {
                   result[partCounter] = partHolder;
                   partCounter++;
                   partHolder = "";
               }
           }
       }
       return 0;
   }
   //Attributes
public:
   //Default constructor
   EvolutionTree() {
       //Initialize empty string array
       for (int i = 0; i < MAX_SIZE; i++) {
           species[i] = "";
       }
       //Initialize age array as 0's
       for (int i = 0; i < MAX_SIZE; i++) {
           speciesAges[i] = 0;
       }
   }
   //Method to load data from file to corresponding arrays
   //Array contain species name and age seperated by comma
   //If file not found return -1
   //Otherwise 0
   int LoadTree(string filename) {
       ifstream in(filename);
       int i = 0;
       string line;
       if (!in) {
           return -1;
       }
       while (getline(in, line)) {
           string result[2];
           split(line, ',', result, 2);
           species[i] = result[0];
           speciesAges[i++] = stoi(result[1]);
       }
       in.close();
       return 0;
   }
   //Search for a species in species array
   //If found return index
   //Otherwise -1
   int SearchForSpecies(string speciesName) {
       for (int i = 0; i < MAX_SIZE; i++) {
           if (species[i] == speciesName) {
               return i;
           }
        }
       return -1;
   }
   //will take in an age and return the corresponding species name.
   //It should return an empty string ("") if the age is not foun
   string GetSpecies(int speciesAge) {
       for (int i = 0; i < MAX_SIZE; i++) {
           if (speciesAges[i] == speciesAge) {
               return species[i];
           }
       }
       return "";
   }
};
//Main function test
int main()
{
   //Class Object
   EvolutionTree tree;
   //Load a file
   if (tree.LoadTree("species.txt")==0) {
       cout << "File loaded successfully\n";
       cout<<"Search for a species using age: "<<tree.GetSpecies(82)<<endl;
       cout << "Search for species 'Cat' found at the index of "
           << tree.SearchForSpecies("Cat") << endl;
   }
   return 0;
}

--------------------------------------------------------------

Output

File loaded successfully
Search for a species using age: Human
Search for species 'Cat' found at the index of 3

-------------------------------------------------------

Note:-

I am using visual studio 2017 as editor.

I assume you are expecting this way


Related Solutions

Java program Create a public method named saveData for a class named Signal that will hold...
Java program Create a public method named saveData for a class named Signal that will hold digitized acceleration data. Signal has the following field declarations private     double timeStep;               // time between each data point     int numberOfPoints;          // number of data samples in array     double [] acceleration = new double [1000];          // acceleration data     double [] velocity = new double [1000];        // calculated velocity data     double [] displacement = new double [1000];        // calculated disp...
List at least 3 criteria by which species are named.
List at least 3 criteria by which species are named.
Create a class named CollegeCourse that includes data fields that hold the department (for example, ENG),...
Create a class named CollegeCourse that includes data fields that hold the department (for example, ENG), the course number (for example, 101), the credits (for example, 3), and the fee for the course (for example, $360). All of the fields are required as arguments to the constructor, except for the fee, which is calculated at $120 per credit hour. Include a display() method that displays the course data. Create a subclass named LabCourse that adds $50 to the course fee....
Java program Create a constructor for a class named Signal that will hold digitized acceleration data....
Java program Create a constructor for a class named Signal that will hold digitized acceleration data. Signal has the following field declarations private     double timeStep;               // time between each data point     int numberOfPoints;          // number of data samples in array     double [] acceleration = new double [1000];          // acceleration data     double [] velocity = new double [1000];        // calculated velocity data     double [] displacement = new double [1000];        // calculated disp data The constructor...
Create a class named Lease with fields that hold an apartment tenant’s name, apartment number, monthly...
Create a class named Lease with fields that hold an apartment tenant’s name, apartment number, monthly rent amount, and term of the lease in months. Include a constructor that initializes the name to “XXX”, the apartment number to 0, the rent to 1000, and the term to 12. Also include methods to get and set each of the fields. Include a nonstatic method named addPetFee() that adds $10 to the monthly rent value and calls a static method named explainPetPolicy()...
Create a file named StudentArrayList.java,within the file create a class named StudentArrayList. This class is meant...
Create a file named StudentArrayList.java,within the file create a class named StudentArrayList. This class is meant to mimic the ArrayList data structure. It will hold an ordered list of items. This list should have a variable size, meaning an arbitrary number of items may be added to the list. Most importantly this class should implement the interface SimpleArrayList provided. Feel free to add as many other functions and methods as needed to your class to accomplish this task. In other...
Create a custom Exception named IllegalTriangleSideException. Create a class named Triangle. The Triangle class should contain...
Create a custom Exception named IllegalTriangleSideException. Create a class named Triangle. The Triangle class should contain 3 double variables containing the length of each of the triangles three sides. Create a constructor with three parameters to initialize the three sides of the triangle. Add an additional method named checkSides with method header - *boolean checkSides() throws IllegalTriangleSideException *. Write code so that checkSides makes sure that the three sides of the triangle meet the proper criteria for a triangle. It...
Create a custom Exception named IllegalTriangleSideException. Create a class named Triangle. The Triangle class should contain...
Create a custom Exception named IllegalTriangleSideException. Create a class named Triangle. The Triangle class should contain 3 double variables containing the length of each of the triangles three sides. Create a constructor with three parameters to initialize the three sides of the triangle. Add an additional method named checkSides with method header - *boolean checkSides() throws IllegalTriangleSideException *. Write code so that checkSides makes sure that the three sides of the triangle meet the proper criteria for a triangle. It...
The Account class Create a class named Account, which has the following private properties:
in java The Account class Create a class named Account, which has the following private properties: number: long balance: double Create a no-argument constructor that sets the number and balance to zero. Create a two-parameter constructor that takes an account number and balance. First, implement getters and setters: getNumber (), getBalance (), setBalan newBalance). There is no setNumber () once an account is created, its account number cannot change. Now implement these methods: void deposit (double amount) and void withdraw (double amount). For both these methods, if the amount is less than...
The Account class Create a class named Account , which has the following private properties:
 The Account class Create a class named Account , which has the following private properties: number: long balance: double Create a no-argument constructor that sets the number and balance to zero. Create a two-parameter constructor that takes an account number and balance. First, implement getters and setters: getNunber(), getBalance(), setBalance (double newBalance) . There is no setNunber() - once an account is created, its account number cannot change. Now implement these methods: void deposit (double anount) and void withdraw(double anount). For both these methods, if the amount is less than zero,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT