Question

For this assignment, suppose that a fence is recording entry and exit into the park via...

For this assignment, suppose that a fence is recording entry and exit into the park via a string as the gate swings open and folks walk in or out with their pet. For example, C++

DP+dp+CP+cp

would indicate that an adult dog and an adult entered the park, then a puppy and child entered the park, then an adult cat and an adult entered the park and finally a kitten and a child entered the park. From this information, note that the character D is being used to represent an adult dog, the character P is being used to represent an adult person, the character d is being used to represent a puppy, the character p is being used to represent a child, the character C is being used to represent an adult cat and the character c is being used to represent a kitten. After processing this string, the park will have a dog and a puppy, a cat and a kitten and two adults and two children left inside. For example,

DP+cp-DP-cp

would indicate that an adult dog and an adult entered the park, then a kitten and a child entered the park, then an adult dog and an adult left the park and then a kitten and a child left the park. After processing this string, the park will not have any dogs, cats or people left inside. For example,

DdPp+ccPP

would indicate that an adult dog and puppy entered the park with an adult and a child followed by two kittens who entered with two adults. After processing this string, the park will have a puppy and an adult dog plus two kittens and three adults and a child left inside.

Precisely, to be a valid animal park string,

- pet(s) must be followed by owner(s)
- pet(s) and owner(s) must leave the park together, but only once they have entered
- cats and dogs cannot be mixed on a single entry into the park
- cats and dogs cannot be mixed on a single exit from the park
- the only characters allowed in string are: + - D d C c   P p No spaces or any other character besides the 6 characters you see listed to the left.
- the string cannot start with +

All of the following are examples of valid animal park strings:

  • CP+dp-CP-dp (no dogs, no cats and no people left in the park after the string is processed)
  • dp+cp (one puppy, one kitten and two children left in the park after the string is processed)
  • CP+dp-CP (one puppy and one child left in the park after the string is processed)
  • ccCP+ddDP (two kittens, one cat, two puppies, one dog and two adults left in the park after the string is processed)
  • dP+dp-ddPp (animals entering separately can leave together, as long as they leave after having entered and dogs and cats are not entering or leaving together)
  • DP+CP+cp+dp-Dp-Cp-dP-cP   (any present group of pets and people can leave, once they have entered the park, whether they arrived with that pet or not)
  • CCP-CP (pets and people in any combination may be left befind after the string is fully processed)

All of the following are examples of invalid animal park strings:

  • asdf1ABC000:2-55    (no characters allowed besides c, C, d, D, p, P, + or -)
  • +dp+cp (no leading + allowed)
  • d p + c p (no spaces allowed)
  • -dp+dp (no leading - allowed and a pet cannot leave before it has entered)
  • dp-CP (a pet cannot leave before it has entered)
  • cCcDP    (dogs and cats cannot be mixed on a single entry into the park)
  • cP+dP-cdPP (dogs and cats cannot be mixed on a single exit from the park)
  • cpP-P   (you cannot leave without having a pet with you)
  • cp+P-cpP    (you cannot enter without having a pet with you)

Your task

For this project, you will implement the following four functions, using the exact function names, parameter types, and return types shown in this specification. (The parameter names may be different if you wish).

bool isValidAnimalParkString(string animalparkString)

This function returns true if its parameter is a well-formed animal park string as described above, or  false otherwise.

int dogsLeft(string animalparkString)

If the parameter is a well-formed animal park string, this function should return the number of dogs (both puppies and adult dogs) left after the string is fully processed. If the parameter is not a valid animal park string, return -1.

int catsLeft(string animalparkString)

If the parameter is a well-formed animal park string, this function should return the number of cats (both kittens and adult cats) left after the string is fully processed. If the parameter is not a valid animal park string, return -1.   

int peopleLeft(string animalparkString)

If the parameter is a well-formed animal park string, this function should return the number of people (both children and adults) left after the string is fully processed. If the parameter is not a valid animal park string, return -1.  

These are the only four functions you are required to write. Your solution may use functions in addition to these four if you wish. While we won't test those additional functions separately, using them may help you structure your program more readably. Of course, to test them, you'll want to write a main routine that calls your functions. During the course of developing your solution, you might change that main routine many times. As long as your main routine compiles correctly when you turn in your solution, it doesn't matter what it does, since we will rename it to something harmless and never call it (because we will supply our own main routine to thoroughly test your functions).

Programming Guidelines

The functions you write must not use any global variables whose values may be changed during execution (so global constants are allowed).

When you turn in your solution, neither of the four required functions, nor any functions they call, may read any input from cin  or write any output to  cout. (Of course, during development, you may have them write whatever you like to help you debug.) If you want to print things out for debugging purposes, write to cerr  instead of cout. cerr  is the standard error destination; items written to it by default go to the screen. When we test your program, we will cause everything written to cerr  to be discarded instead — we will never see that output, so you may leave those debugging output statements in your program if you wish.

The correctness of your program must not depend on undefined program behavior. For example, you can assume nothing about  c 's value at the point indicated, nor even whether or not the program crashes:

        int main()
        {
            string s = "Hello";
            char c = s[5];   // c's value is undefined
            …

Be sure that your program builds successfully, and try to ensure that your functions do something reasonable for at least a few test cases. That way, you can get some partial credit for a solution that does not meet the entire specification.

There are a number of ways you might write your main routine to test your functions. One way is to interactively accept test strings:

        int main()
        {
            string s;
cout.setf( ios::boolalpha ); // prints bool values as "true" or "false"

for(;;) { cout << "Enter a possible animal park string: "; getline(cin, s); if (s == "quit") break; cout << "isValidAnimalParkString returns "; cout << isValidAnimalParkString(s) << endl; cout << "dogsLeft(s) returns "; cout << dogsLeft(s) << endl; cout << "catsLeft(s) returns "; cout << catsLeft(s) << endl; cout << "peopleLeft(s) returns "; cout << peopleLeft(s) << endl; }

            return 0;
        }

While this is flexible, you run the risk of not being able to reproduce all your test cases if you make a change to your code and want to test that you didn't break anything that used to work.

Another way is to hard-code various tests and report which ones the program passes:

        int main()
        {
            if (!isValidAnimalParkString(""))
                cout << "Passed test 1: !isValidAnimalParkString(\"\")" << endl;
            if (!isValidAnimalParkString("   "))
                cout << "Passed test 2: !isValidAnimalParkString(\"   \")" << endl;
            …

This can get rather tedious. Fortunately, the library has a facility to make this easier:  assert . If you #include the header <cassert> , you can call assert  in the following manner:

        assert(some boolean expression);

During execution, if the expression is true, nothing happens and execution continues normally; if it is false, a diagnostic message is written to cerr telling you the text and location of the failed assertion, and the program is terminated. As an example, here's a very incomplete set of tests:

        #include <cassert>
        #include <iostream>
        #include <string>
        using namespace std;

        …

        int main()
        {
            assert( ! isValidAnimalParkString(""));
            assert( ! isValidAnimalParkString("    "));
            assert( dogsLeft( "    " ) == -1 );
            assert( peopleLeft( "      " ) == -1 );
            assert( isValidAnimalParkString( "CP+dp" ) == true );
            assert( dogsLeft( "dp+DP" ) == 2 );
            assert( peopleLeft( "dp+DP" ) == 2 );
            assert( catsLeft( "dp+DP" ) == 0 );
            assert( catsLeft( "CP+cp-CP" ) == 1 );
            …
            cerr << "All tests succeeded" << endl;
            return 0;
        }

The reason for writing one line of output at the end is to ensure that you can distinguish the situation of all tests succeeding from the case where one function you're testing silently crashes the program.

    1. Create a function that reads a single animal character c, C, d or D. HINT: such a function was supplied in class
    2. Use this function to read the opening pet from the animal park string. If it fails to find an animal character, the string is not a valid animal park string.
    3. Create a function that reads a single person character p or P.
    4. Use this second function to read a person character after reading the opening pet from the animal park string. If it fails to find an person character, the string is not a valid animal park string.
    5. Like the previous simplification, but make sure a + or - follows the person character.
    6. Build a loop in your functions so you can read more than one pet or person. Adjust your function arguments your code returns the number of pets or people it has read.
    7. Build a loop in your code so that you can repetitively read + or - followed by an animal character followed by a person character.
    8. As your code loops, track the number of dogs, puppies, cats, kitten, adults and children. Make sure that none of these numbers go negative.
    9. Make sure once your code stops looping that the string is fully read all the way to the end of the string.
    10. Be sure not to go off the edge of your animal park string.  
  1. Now that isValidAnimalParkString is correctly implemented, proceed in a similar fashion to implement dogsLeft, starting with an extreme simplification, then working your way through successive removals of simplifying assumptions. Proceed in a similar fashion to implement catsLeft and the other function. And yes, these later functions can call the isValidAnimalParkString as part of what they do. This is intended to show you the power of reuse, a key benefit to writing modularized code with functions.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

The required c++ program is given below. The explanations are provided as comments:

#include<string.h>
#include<ctype.h>
#include<assert.h>
#include<iostream>
using namespace std;
//function to check if the string
//contains only permitted characters
bool checkChar(string s)
{
   for(int i = 0; i<s.size(); i++)
   {
       if(tolower(s[i])=='c'||tolower(s[i])=='d'||tolower(s[i])=='p'||s[i]=='+'||s[i]=='-')
           continue;
       else return false;
   }
   return true;  
}
//function to check if a character
//is a pet
bool checkAnimal(char c)
{
   if(c=='C'||c=='c'||c=='D'||c=='d') return true;
   return false;
}
//function to chech if a character
//is a person
bool checkPeople(char c)
{
   if(c=='P'||c=='p') return true;
   return false;
}
//function to chech if a character
//is + or -
bool checkSymbol(char c)
{
   if(c=='+'||c=='-') return true;
   return false;
}
//function to count a character
//in a string
int charCount(string s, char c)
{
   int count = 0;
   for(int i=0; i<s.size(); i++)
   {
       if(s[i]==c) count++;
   }
   return count;
}
//function to check if the string
//is valid
bool isValidAnimalParkString(string s)
{
   int entryCount = 0, exitCount = 0;
   char entryChar[100], exitChar[100];
   bool enter=true;
   //check if string contains only allowed string
   if(!checkChar(s)) return false;
   //check if string is empty
   if(s.size()==0) return false;
   for(int i=0;i<s.size();i++)
   {
   //check if first character is + or -
       if(i==0&&checkSymbol(s[i])) return false;
       //check if there is a pet in the beginning
       if(i==0&&!checkAnimal(s[i])) return false;
       //check if the character is a space
       if(s[i]==' ')return false;
       //check if dogs and cats enter together
       if(checkAnimal(s[i-1])&&(checkAnimal(s[i]))&&!(tolower(s[i-1])==tolower(s[i])))
           return false;
       //check if people enter without pets
       if(checkSymbol(s[i-1])&&checkPeople(s[i])) return false;
       //check whether character enters or exits
       if(s[i]=='+') enter = true;
       if(s[i]=='-') enter = false;
       //check for a pet's entry
       if(enter&&checkAnimal(s[i]))
       {
           entryChar[entryCount]=s[i];
           entryCount++;
       }
       //check for a pet's exit
       if((!enter)&&checkAnimal(s[i]))
       {
       //check if a pet exits before entering
           if((charCount(entryChar,s[i])-charCount(exitChar,s[i]))==0)
               return false;
           exitChar[exitCount] = s[i];
           exitCount++;
       }
   }
   return true;
}

//function to count the no. of dogs and puppies
//inside park
int dogsLeft(string s)
{
   int entryCount = 0, exitCount = 0;
   bool enter = true;
   if(!isValidAnimalParkString(s)) return -1;
   for(int i=0; i<s.size(); i++)
   {
       if(s[i]=='+') enter = true;
       if(s[i]=='-') enter = false;
       if(enter&&(tolower(s[i])=='d'))
       {
           entryCount++;
       }
       if((!enter)&&(tolower(s[i])=='d'))
       {
          
           exitCount++;
       }
   }
   return entryCount-exitCount;
}

//function to count the no. of cats and kittens
//inside park
int catsLeft(string s)
{
   int entryCount = 0, exitCount = 0;
   bool enter = true;
   if(!isValidAnimalParkString(s)) return -1;
   for(int i=0; i<s.size(); i++)
   {
       if(s[i]=='+') enter = true;
       if(s[i]=='-') enter = false;
       if(enter&&(tolower(s[i])=='c'))
       {
           entryCount++;
       }
       if((!enter)&&(tolower(s[i])=='c'))
       {
          
           exitCount++;
       }
   }
   return entryCount-exitCount;
}

//function to count the no. of people
//inside park
int peopleLeft(string s)
{
   int entryCount = 0, exitCount = 0;
   bool enter = true;
   if(!isValidAnimalParkString(s)) return -1;
   for(int i=0; i<s.size(); i++)
   {
       if(s[i]=='+') enter = true;
       if(s[i]=='-') enter = false;
       if(enter&&(tolower(s[i])=='p'))
       {
           entryCount++;
       }
       if((!enter)&&(tolower(s[i])=='p'))
       {
          
           exitCount++;
       }
   }
   return entryCount-exitCount;
}

int main()
{
   assert( ! isValidAnimalParkString(""));
assert( ! isValidAnimalParkString(" "));
assert( dogsLeft( " " ) == -1 );
assert( peopleLeft( " " ) == -1 );
assert( isValidAnimalParkString( "CP+dp" ) == true );
assert( dogsLeft( "dp+DP" ) == 2 );
assert( peopleLeft( "dp+DP" ) == 2 );
assert( catsLeft( "dp+DP" ) == 0 );
assert( dogsLeft( "DP+cp-DP" ) == 0 );
cerr << "All tests succeeded";
return 0;
}

That concludes the solution, if you have any doubts or you need more information, please reach out to me in comment section.

Add a comment
Know the answer?
Add Answer to:
For this assignment, suppose that a fence is recording entry and exit into the park via...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I USE NETBEANS. C++ PLEASE. COULD YOU PLEASE WRITE A CODE THAT ACTUALLY WORKS, PLEASE PLEASE PLEA...

    I USE NETBEANS. C++ PLEASE. COULD YOU PLEASE WRITE A CODE THAT ACTUALLY WORKS, PLEASE PLEASE PLEASE EXPLAIN WHAT EVERYTHING IS DOING. INCLUDE SCREENSHOTS OF OUTPUTS PLEASE. I REALLY APPRECIATE THE HELP. THANK YOU <3 100% RATING IF CORRECT AND IS UNDERSTANDABLE. PLEASE ONLY CODES THAT WORK AND DO THE TASK AT HAND. 2 Write code for these functions using the string API: A boolean function no_el1 that takes a string as parameter and returns true if the string does...

  • trouble with formatting titles :( Your friend is in charge of recording titles of books in...

    trouble with formatting titles :( Your friend is in charge of recording titles of books in the library they work in. Since they know you're in EECS 183, they've asked you to write a function that turns a lowercase string into Title Case format. This way, they can use the function to correctly format the titles without having to worry about capitalizing anything themselves. The function you will implement is stringToTitleCase, which takes a lowercase string str as input and...

  • /// c ++ question plz help me fix this not a new code and explain to...

    /// c ++ question plz help me fix this not a new code and explain to me plz /// Write a function to verify the format of an email address: bool VeryifyEmail(char email[ ]); Do NOT parse the email array once character at a time. Use cstring functions to do most of the work. Take a look at the available cstring and string class functions on cplusplus website. Use a two dimensional array to store the acceptable top domain names:...

  • class AVLTree The following functions are the minimum requirements for the AVL class. You can add...

    class AVLTree The following functions are the minimum requirements for the AVL class. You can add any function from Assignment 2 to this class. You should modify the BSTree insert function so that the tree remains balanced after each insertion. Required Public Member Functions void insert(const string &): Insert an item to the binary search tree and perform rotation if necessary. int balanceFactor(Node*): Return the balance factor of a given node. void printBalanceFactors(): Traverse and print the tree in inorder...

  • I need help with this assignment, can someone HELP ? This is the assignment: Online shopping...

    I need help with this assignment, can someone HELP ? This is the assignment: Online shopping cart (continued) (C++) This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program). (1) Extend the ItemToPurchase class per the following specifications: Parameterized constructor to assign item name, item description, item price, and item quantity (default values of 0). (1 pt) Public member functions SetDescription() mutator & GetDescription() accessor (2 pts) PrintItemCost() - Outputs the item name followed by...

  • Help C++ Write a string class. To avoid conflicts with other similarly named classes, we will...

    Help C++ Write a string class. To avoid conflicts with other similarly named classes, we will call our version MyString. This object is designed to make working with sequences of characters a little more convenient and less error-prone than handling raw c-strings, (although it will be implemented as a c-string behind the scenes). The MyString class will handle constructing strings, reading/printing, and accessing characters. In addition, the MyString object will have the ability to make a full deep-copy of itself...

  • Program is in C++, program is called airplane reservation. It is suppose to display a screen...

    Program is in C++, program is called airplane reservation. It is suppose to display a screen of seating chart in the format 1 A B C D E F through 10. I had a hard time giving the seats a letter value. It displays a correct screen but when I reserve a new seat the string seats[][] doesn't update to having a X for that seat. Also there is a file for the struct called systemUser.txt it has 4 users...

  • Hello, I need help with this question please. you have to do the concession, signal word...

    Hello, I need help with this question please. you have to do the concession, signal word and refutation in one paragraph or lines Thank you The Counter-argument: Exercise the following argument essay and add a counterargument Directions Read eto use the 3 elements: Concession to acknowledgaragraph Sumembher i to show contrast, and refutation to return back to your thesis before opposing viewpoint, nning the next paragraph "Fixing" What Isn't Brokenis t r knows that there are enormous responsibilities that go...

  • Objectives: The main objective of this assignment is checking students’ ability to implement membership functions. After...

    Objectives: The main objective of this assignment is checking students’ ability to implement membership functions. After completing this assignment, students will be able to:  implement member functions  convert a member function into a standalone function  convert a standalone function into a member function  call member functions  implement constructors  use structs for function overloading Problem description: In this assignment, we will revisit Assignment #1. Mary has now created a small commercial library and has managed...

  • C++ Programming - Design Process I need to create a flow chart based on the program...

    C++ Programming - Design Process I need to create a flow chart based on the program I have created. I am very inexperienced with creating this design and your help will be much appreciated. My program takes a string of random letters and puts them them order. Our teacher gave us specific functions to use. Here is the code: //list of all the header files #include <iomanip> #include <iostream> #include <algorithm> #include <string> using namespace std; //Here are the Function...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT