Você está na página 1de 26

Group 1 1. The price of an item you want to buy is given in dollars and cents.

You pay for it in cash by giving the clerk d dollars and c cents. Write specications for a function that computes the change, if any, that you should receive. Include a statement of purpose, the preconditions and post conditions, and a description of the arguments. Ans. Statement of purpose: A C++ function that accepts the total Price in Dollars and cents and payment in cash, and returns a change Precondition: Call to this function passed with a non-void Price in correct sequence (Dollars, cents), non-void argument of user change(Dollars, Cents),iostream should be there to define cout and cerr. Post-Condition: The Output passed by this function, is displayed correctly. The code specification is below: int function(int pd, int pc, int dd, int dc){ if (pd+pc) if((pd+pc)>(dd+dc)) float change = pd+pc/100-dd-dc/100; int changedoll =float(change); float changecent= 100* (change changedoll) else cout<<"insufficient balance"<<endl; bill.changedisplay(Change is &changedoll dollars, &changecent cents) bill.change(&changedoll, &changecent); else cerr<<"Goods cannot be free"; return(1); }

3. Write a pseudo code function in terms of the ADT appointment book, described in Section 1.4.1, for each of the following tasks. Do you need to add operations to the ADT to perform these tasks? a. Change the purpose of the appointment at a given date and time. b. Display all the appointments for a given date. ChangeAppointmentPurpose(AB, Date, Time, Purpose, Success) if(AB.IsAppointment(Date, Time)) AB.CancelAppointment(Date, Time, Success) AB.MakeAppointment(Date, Time, NewPurpose, Success) DisplayAllAppointments(AB, Date, Success) Time = Bday while(Time < EndDay) if(AB.IsAppointment(Date, Time)) AB.DisplayAppointment(Date, Time, Success) Time = Time + HalfDay This implementation requires the definition of a new operation, DisplayAppointment(), as well as definitions for the constants Bday, EndDay and HalfDay.

4. Imagine that you have just left a store with a bag of groceries. You are concerned that the fragile items will not survive the trip home, so when you reach your car, you place those items into their own bag. If Bag is a class of bags, write C++ statements that remove all the items from storeBag and place them into one of two new bags, as follows: Place all occurrences of bread and eggs into fragileBag, and all other items into groceryBag. When you are done, storeBag should be empty. Assume that grocery items are represented by strings.

Void bag::sort(char *items){ std::string token = s.substr(0, s.find( )); pos=0; while (token!= items){ If (token==bread)|| (token== eggs){ bag.assign( FragileBag, &pos) /*assigns serial number of item into fragilebag*/ } else bag.assign(Grocerybag, &pos) ++pos; std::string token = s.substr(pos), s.find( )); } bag.delete(storebag);//calls a method of class storebag (whose friend our method is). Most compilers would not support delete <object> }

5. Suppose that a bag contains strings that represent various grocery items. Write a C++ function that removes and counts all occurrences of a given string from such a bag. Your function should return this number. Use comments in javadoc style to fully specify your function. Accommodate the possibility that the given bag is either empty or does not contain any occurrences of the given string.

Group 2 4. Given two integers, start and end , where end is greater than start , write a recursive C++ function that returns the sum of the integers from start through end , inclusive.

/*In real lyf we have formulae*/ int troll(int pd,int pc){ if (pd!=pc){ pd=2*pd+1; troll(pd,pc); } else{ return(pd); } }

8. Given an integer n> 0, write a recursive C++ function that returns the sum of the squares of 1 through n int troll(int pd,int pc){ if (pd^2!=pc^2){ /*thats right, reusability is why we have included pow here)*/ pd=pd+pd^2; troll(pd,pc); } else{ return(pd); } } #18 only below

Group # 3 1. Consider a bag of integers. Write a client function that computes the sum of the integers in the bag aBag .
int AddList(listClass& L) // ---------------------------------------------------------// Computes the sum of the integers in the list L. // Precondition: L is a list of integers. // Postcondition: The sum of the integers in L is returned. // ---------------------------------------------------------{ int Sum = 0, NextItem; boolean Success; for(int I = 1; I <= L.ListLength(); ++I) { // Invariant: Sum is the total of the first // I elements in L.

Success = true; L.ListRetrieve(I, NextItem, Success); if(Success) Sum += NextItem; } // end for }

2. Write a client function replace that replaces a given item in a given bag with another given item. The function should return a boolean value to indicate whether the replacement was successful. //already discussed 4. Design and implement an ADT that represents a rectangle. Include typical operations, such as setting and retrieving the dimensions of the rectangle, and nding the area and the perimeter of the rectangle. class Rectangle { private: int width; int length; public: void set(int w, int l); int area(); } 5. Design and implement an ADT that represents a triangle. The data for the ADT should include the three sides of the triangle but could also include the triangles three angles. This data should be in the private section of the class that implements the ADT. Include at least two initialization operations: one that provides default values for the ADTs data, and another that sets this data to client-supplied values. These operations are the classs constructors. The ADT also should include operations that look at the values of the ADTs data; change the values of the ADTs data; compute the triangles area; and determine whether the triangle is a right triangle, an equilateral triangle, or an isosceles triangle. Ans.

using shapetype=char *; class traingle { protected: double double double public: shapetype type1; /* type of shape (T_TRIANGLE) */ float area; triangle( float x1,float y1,float x2,float y2, float x3, float y3) { triangle.getshape([x1,x2,x3],[y1,y2,y3]); }//constructor ~triangle(),//destructor x1, y1; /* coordinates of the corners */ x2, y2; x3, y3;

void triangle::getshape (int *a, int *b){ int *l; shapetype type1; shapetype type2; for (int i=1,i=3,i++){ (i!=3)?(l[i]= (a[i+1]-a[i])^2+(b[i+1]-b[i])^2)||(l[i]=(a[1]-a[3])^2 +(b[1]-b[3])^2); } if ((l[1]==l[2])||(l[1]==l[3]){ (l[2]=l[3])? type1=="Equilateral"||type1="Isosceles";

} else if (l[2]=l[3]){ type1= "Isosceles" } (2*max(l)>sum(l))?type2="obtuse angled"|| (2*max(l)=sum(l)?type2="rightangled")||type2="acute angled"; type=[type1,type2] area= }

Group 4; 2. Revise the public method add in the class LinkedBag so that the new node is inserted at the end of the linked chain. 4. Revise the public method getFrequencyOf in the class LinkedBag so that it is recursive. 6. Specify and dene a method for LinkedBag that removes a random entry from the bag. 8. Compare the number of operations required to display the data in the nth node in a linked chain with the number of operations required to display the nth item in an array. 10. In a doubly linked chain , each node can point to the previous node as well as to the next node. Figure 4-9 shows a doubly linked chain and its head pointer. Dene a class to represent a node in a doubly linked chain. 12. List the steps necessary to remove the rst node from the beginning of the doubly linked chain shown in Figure 4-9 .

Figure 4-9 (do not work problems in print screen below)

Group 5: 1. If headPtr is a pointer variable that points to the rst node of a linked chain of at least two nodes, write C++ statements that delete the second node and return it to the system.

void DeleteNode (ptrType& Head) { ptrType Cur; if (a<3){ Cur = Head->Next; delete Cur;

} 3. Suppose that the class LinkedBag did not have the data member itemCount. Revise the method getCurrentSizesof that it counts the number of nodes in the linked chain a. Iteratively template<typename T> //type independance int Linkedbag<T>::getsizeof(T){ private: Node<T>* current=start; short int i=0; //iteration while (current!=null){ current=current->next; i++ } return(i); } //head

b. Recursively template<typename T> //type independance int Linkedbag<T>::getsizeof(T){ Node<T>* current=start; current= current->next (current==Null)?return(1)||Linkedag.getsizeof(T,1, &current) //head

int Linkedbag<T>::getsizeof(T, int i, long int current){

if (current=null){

return(i) } else { i++;

current= current->next; Linkedag.getsizeof(T,1, &current) }

} 5. Add a constructor to the class LinkedBag that creates a bag from a given array of entries. void LinkedBag::LinkedBag(char *a){ public: char i; item=a; next=1:sizeof(a)/sizeof(*a); }

6. Specify and dene a method for LinkedBag that removes a random entry from the bag. template<typename T> bool LinkedBag<T>::RemoveMid(T& target) { Node<T> *current = new Node<T>; bool found = false; current = start; while(current != NULL && !found) { if(current->next->info == target) found = true; if(!found) current = current->next; } if(found) { Node<T> *Ptr; Ptr = current->next; current = current->next;

delete Ptr; return true; } else cout<<"target not found\n";

9. Compare the array-based and link-based implementations of the ADT bag operation remove(anEntry). Consider the various locations of an Entry within the array or chain. First of all everything depends on whether ADT is declared as array or linkedlist. the absolute deviation of maxsize less minsize determines. Strongly linked lists would start from head, others might have a tailptr. However in both the cases we have to move a pointer to the address of the ith entry and delte. In array based implementation complexity is reduced, we can just replace concents of the array from the ith position by contents of i+1th position. Ans. While array based implementation have a slight difference in computation time, more than half the time is saved for search based implementation, arrays have serious delimits as their vector size is fixed. Memory management is retarded.

11. List the steps necessary to add a node to the beginning of the doubly linked chain shown in Figure 4-9 .

LinkedList Add To Front

Now if we add another node at the front of this Linked list then we need to do 2 things.

Assign next to new item. Set the headptr to this node. Tailptr remains unchanged.

Group 6:

1. What is meant by a grammar? 2. Describe what <word> means in terms of a grammar. String formed from this alphabets, an element of a finite set of symbols, letters, or tokens are called word. <word> defines word to be part of a formal language, thus declaring a word to be well formed. 3. What is the main benefit of using a grammar that Recursion that allows to produce infinite sets of words, in most grammars. is recursive?

4. What are the two base cases in a recursive description of a palindrome? 1. Word: Needs to be a palindrome, before progress. 2. Collection of Words: Prove by Induction: Collection of palindromes a palindrome. 5. What is an empty string?
The empty string has several properties:

. The string length is zero. . The empty string is the identity element of the union operation. Also, pre-appending and post appending the string gives identical results, Union possible. . Reversal of the empty string produces the empty string.

6. What is a fully parenthesized infix expression? This involves operations between two constants enclosed in parenthesis to avoid the BODMAS complication. Example: ((2*5)+(6/2))

7. What is an infix expression? Any expression of form object operator object eg 22+32*43. Not easy to interpret, vis a vis.. fully parenthesized case. 8. What is a postfix expression? Ans. 22+ c++. An expression asking for incrementing or decrementing a value by one unit, after the loop is over. 9. What is a prefix expression? Ans. ++22, ++c :An expression with increment or decrement preceding the integer, tells us this has to be done NOW. 10. How can precedence and association rules be avoided in infix notation? Ans.

By generating a fully parenthesized case. Next using stack, convert Infix to Postfix.. which can be easily implemented by compiler.

11. What is the advantage of using prefix or postfix expressions instead of infix expressions?
1. Trace the following recursive functions: a. isPal with the string abcdeba Ans.

W = abcdeba W = abcdeba W = bcdeb W = abcdeba W = bcdeb W = cde W = abcdeba W = bcdeb W = cde return false; W = abcdeba W = bcdeb return false; W = cde return false; W = abcdeba return false; W = bcdeb return false; W = cde return false; b. isAnBn with the string AABB

The initial call is made and the function begins execution: The call to IsAnBn(AB) is made: The call to IsAnBn() is made: 5 W = abcdeba W = abcdeba W = bcdeb W = abcdeba W = bcdeb W = cde W = abcdeba W = bcdeb W = cde return false; W = abcdeba W = bcdeb return false; W = cde return false; W = abcdeba return false; W = bcdeb return false; W = cde return false; W = AABB W = AABB W = AB W = AABB W = AB W = 50

Base case: W = empty string, returns true: The call IsAnBn(AB) returns true: The call IsAnBn(AABB) returns true and the initial call completes. 1c The call EndPre(-*/ABCD) produces the following box trace: S = -*/ABCD; W = AABB First = 0 Last = 6 X:EndPre(S,1,6) W = AB First = 1 Last = 6 FirstEnd = 4 Y:EndPre(S,5,6) W = return true; First = 5 Last = 6 W = AABB W = AB return true; W = return true; W = AABB return true; W = AB

return true; W = return true;

c. endPre with the expression */ abcd

2. Consider the language that the following grammar denes: ,S. 5 $0,W. 0$ ,S. ,W. 5 abb0a ,W. bb Correct Expression:

Write all strings that are in this language and that contain seven or fewer characters. The rules are clear $s precede a, and bs; a precede ist occurrence of b, words end with b The list of all possible permutations subject to max of 7 characters are

3. Write a recursive grammar for the language of strings of one or more letters. The rst letter of each string must be uppercase, and all other letters in the string must be lowercase.

4. Consider a language of character strings that contain only dots and dashes. All strings in this language contain at least four characters and begin with either two dots or two dashes. If the rst two characters are dots, the last one must be a dash; if the rst two characters are dashes, the last one must be a dot. Write a recursive grammar for this language.

5. Consider a language of strings that contains only X s, Y s and Z s. A string in this language must begin with an X . If a Y is present in a string, it must be the nal character of the string. a. Write a recursive grammar for this language. b. Write all the possible two-character strings of this language. a. <S>= X|<W>|<W> <W>=ZY|Z<W>. b. XX XZ XY

6. Consider a language of words, where each word is a string of dots and dashes. The following grammar describes this language:

a. Write all three-character strings that are in this language. _.. --. ... b. Is the string in this language? Explain. - Cannot be at the end of a word. It is always followed vy., when used. c. Write a seven-character string that contains more dashes than dots and is in the language. Show how

you know that your answer is correct.

- - - - . -. - precede .s
d. Writepseudocode for a recursive recognition function isIn(str) that returns true if the string str is in this language and returns false otherwise.

IsIn(s) // Returns true if S is in the indicated language, false otherwise Size = length of string S if(Size == 1 and S[0] == Dot) return true else if (Size > 1 and S[0] == Dash) return IsIn( S minus first character ) else if (Size > 1 and S[Size - 1] == Dot) return IsIn( S minus last character) else return false

7. Consider the following grammar: ,word. 5 R0,D.0,D. ,word. ,S. ,D. ,S. 5 Q0P 51

Write pseudocode for a recursive function that returns true if a string is in this language and returns false otherwise

8. Consider the following grammar: ,G. 5 empty string 0,E.0,V. ,E. 0 ,E. ,G. ,V. ,E. 5 &0# ,V. 5 W0A a. Writepseudocode for a recursive function that returns true if a string is in this language and returns false otherwise. b. Is the string &W#W in this language?

9. Let L be the language

Thus, a string is in L if and only if it starts with a sequence of A s and is followed by a sequence of twice as many B s. For example, AABBBB is in L , but ABBB, ABBABB, and the empty string are not. a. Give a grammar for the language L . Ans. L = {S: <S>= AnB2n, for some n > 0} Grammar would be given below: <S> = ABB | A <S> BB b. Write a recursive function that determines whether the string strExp is in L . // Precondition: none.

#include <string.h> const int MAX_LENGTH = 80; typedef char stringType[MAX_LENGTH]; typedef int boolean;//

// Postcondition: returns true if S is in L, false otherwise.//

boolean IsInL(stringType S) // Determines it the string S is in the language L. { int Size = strlen(S); if (Size < 3) // no strings shorter than 3 are in L. return false;

else if (strcmp(S, "ABB") == 0) // base case return true; else { stringType Substring; // trim off first and last two characters of S strncpy(Substring, &S[1], Size - 3); return IsInL(Substring); } } 10. Is +* a b / c ++ de fg a prex expression? Explain in terms of the grammar for prex expressions. Ans. Yes it is. Consider the first operator It preceeds the variable in the expression. Operators can be meaningfully assigned only when we consider that operators are preceding operands. a*(b-c)/(d+e)+(f-g) 11. Is ab /c * efg * h /+d + a postx expression? Explain in terms of the grammar for postx expressions. Ans. For every operator there exists and operand to the left, the ending expressions are of operands. This expression is in Postfix.

12. Consider the language that the following grammar denes:

a. Write all three-character strings that are in this language. AAA AAB

ABB AB1

b. Write one string in this language that contains more than three characters. AB112AB

Group 7:

1. What is backtracking?

1. Backtracking starts with an empty vector (we assume we know the limiting size (including null element of such vectors). At each stage it extends the partial vector with a logically next value. If the solution is true, it stops Else, upon reaching a partial vector (v1, ..., vi) which cant represent a partial solution, the algorithm backtracks by removing the trailing value from the vector, and then proceeds by trying to extend the vector with alternative values. Pseudo-code:
try(v1,...,vi) IF (v1,...,vi) is a solution THEN RETURN (v1,...,vi) FOR each v DO IF (v1,...,vi,v) is acceptable vector THEN sol = try(v1,...,vi,v) IF sol != () THEN RETURN sol END END RETURN () Applications: Traversing Salesperson problem, Sudoko, 8 Queens problem.

1. 2. When is the base case of the Eight Queens problem reached? Ans. Base Case of the 8-Queen Problem requiring Backtracking would theoretically generate

8! Permutations, for each Queen calculate infeasible position for 7 queens and check the vector. The complexity would be o(8!) Heres a heuristic search Write separate lists of even and odd numbers (i.e. 2,4,6,8 - 1,3,5,7) If the remainder is 2, swap 1 and 3 in odd list and move 5 to the end (i.e. 3,1,7,5) If the remainder is 3, move 2 to the end of even list and 1,3 to the end of odd list (i.e. 4,6,8,2 - 5,7,9,1,3) Append odd list to the even list and place queens in the rows given by these numbers, from left to right (i.e. a2, b4, c6, d8, e3, f1, g7, h5)

4 steps. O(4) 3. What is a recognition algorithm? A recognition algorithm is the assigns a set of labels to a given input value. Pattern recognition algorithms intend to take in a class of inputs and to perform "most likely" (Maximum likelihood or some other class of estimators) matching of the inputs, taking into account their statistical variation. They might be supervised, where learning takes place, involving role of an operator Or Unsupervised. Face, Jesture, Speech, Image recognition algorithms, or even the Google search engine that classifies synonyms or subjects are examples of pattern recognition algorithms. 4. What is a closed-form formula? We define an elementary function as a function of one variable built from a finite number of exponentials, logarithms, constants, and nth roots through composition and combinations using the four elementary operations. A closed form formula would be decomposable into a finite set of operations involving elementary functions.

Você também pode gostar