ObjectTree and Bag Implementation in Java: Methods and Exercises, Assignments of Data Structures and Algorithms

The implementation of various methods related to objecttree and bag data structures in java. The methods include isbalanced, isbst, labelbinaryaddress, labelpreorderaddress, testtree, and teststring. The document also includes instructions for changing the implementation of the nextelement method to enumerate tree elements in post-order and creating a bagentry class. Additionally, there are notes on objecttree and objecttreeops contracts and appendices with their respective contracts.

Typology: Assignments

Pre 2010

Uploaded on 08/17/2009

koofers-user-lbm
koofers-user-lbm 🇺🇸

5

(3)

10 documents

1 / 19

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CS230 Data Structures Handout # 20
Prof. Lyn Turbak November 3, 2004
Wellesley College
Problem Set 6
Due: 6pm Friday, November 12
Exam 2 Notice:
On Friday, November 12, the second take-home exam will be posted. It will be due at 6pm on
Saturday, November 20. This is a hard deadline. No extensions will be given after this
time.1The exam will cover the material in lecture through Lecture 18 (Mon. November 8) and the
material in problem sets through PS6, mainly focusing on material introduced since the last exam:
binary trees and contracts and implementations of stacks, queues, priority queues, sets, bags, and
tables. Because you should focus on the exam, it is strongly recommended that you submit PS6
on time, although you may use lateness coupons to turn in PS6 late. But since the exam is worth
much more than the problem set, it might be best to cut your losses on PS6 if you are not done
with it so that you can focus on the exam.
Overview:
The purpose of this assignment is to give you practice with manipulating trees and implementing
collections via trees.
Working Together:
If you worked with a partner on a previous problem set and want to work with a partner on this
assignment, you are encourage to choose a different partner. However, you may also work with
someone you worked with in the first half of the semester.
Submission:
Each team should turn in a single hardcopy submission packet for all problems by slipping it
under Lyn’s office door by 6pm on the due date. The packet should include:
1. a team header sheet (see the end of this assignment for the header sheet) indicating the time
that you (and your partner, if you are working with one) spent on the parts of the assignment;
2. For Problem 1, submit your final version of PS6TreeOps.java and a transcript of running
java PS6TreeOps.
3. For Problem 2, submit your pencil-and-paper drawings from part a, your final versions of
PostOrderElts.java (part b) and BreadthFirstElts.java (part c), and your testing tran-
scripts showing that these work as expected.
4. For Problem 3, submit your final version of BagMBSTEntries.java and a transcript of running
java BagMBSTEntries.
Each team should also submit a single softcopy (consisting of your final ps6 directory) to the
drop directory ~cs230/drop/ps6/username, where username is the username of one of the team
members (indicate which drop folder you used on your hardcopy header sheet). To do this, execute
the following commands in Linux in the account of the team member being used to store the code.
cd /students/username/cs230
cp -R ps6 ~cs230/drop/ps6/username/
1Especially since the Red Sox season is over!
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13

Partial preview of the text

Download ObjectTree and Bag Implementation in Java: Methods and Exercises and more Assignments Data Structures and Algorithms in PDF only on Docsity!

CS230 Data Structures Handout # 20 Prof. Lyn Turbak November 3, 2004 Wellesley College

Problem Set 6

Due: 6pm Friday, November 12

Exam 2 Notice: On Friday, November 12, the second take-home exam will be posted. It will be due at 6pm on Saturday, November 20. This is a hard deadline. No extensions will be given after this time.^1 The exam will cover the material in lecture through Lecture 18 (Mon. November 8) and the material in problem sets through PS6, mainly focusing on material introduced since the last exam: binary trees and contracts and implementations of stacks, queues, priority queues, sets, bags, and tables. Because you should focus on the exam, it is strongly recommended that you submit PS on time, although you may use lateness coupons to turn in PS6 late. But since the exam is worth much more than the problem set, it might be best to cut your losses on PS6 if you are not done with it so that you can focus on the exam.

Overview: The purpose of this assignment is to give you practice with manipulating trees and implementing collections via trees.

Working Together: If you worked with a partner on a previous problem set and want to work with a partner on this assignment, you are encourage to choose a different partner. However, you may also work with someone you worked with in the first half of the semester.

Submission: Each team should turn in a single hardcopy submission packet for all problems by slipping it under Lyn’s office door by 6pm on the due date. The packet should include:

  1. a team header sheet (see the end of this assignment for the header sheet) indicating the time that you (and your partner, if you are working with one) spent on the parts of the assignment;
  2. For Problem 1, submit your final version of PS6TreeOps.java and a transcript of running java PS6TreeOps.
  3. For Problem 2, submit your pencil-and-paper drawings from part a, your final versions of PostOrderElts.java (part b) and BreadthFirstElts.java (part c), and your testing tran- scripts showing that these work as expected.
  4. For Problem 3, submit your final version of BagMBSTEntries.java and a transcript of running java BagMBSTEntries.

Each team should also submit a single softcopy (consisting of your final ps6 directory) to the drop directory ~cs230/drop/ps6/username, where username is the username of one of the team members (indicate which drop folder you used on your hardcopy header sheet). To do this, execute the following commands in Linux in the account of the team member being used to store the code.

cd /students/username/cs cp -R ps6 ~cs230/drop/ps6/username/ (^1) Especially since the Red Sox season is over!

Problem 1 [40]: ObjectTree Methods In this problem, you will define four methods that manipulate immutable binary trees of objects. Skeletons for these methods appear in the file ps6/PS6TreeOps.java, which you can access after you perform a cvs update -d. For this problem, it is helpful to know a number of definitions. The sample tree T below will be used as an example in many of the definitions:

B

C G

D

E F

H

We adopt the convention of not showing leaf nodes in our tree diagrams.

  • The height of a tree is the longest number of edges from the root to a leaf. The height of T is 4.
  • A tree is balanced if for every node the height of its two subtrees differ by no more than one. T is not balanced because its left subtree has height 1 and its right subtree has height 3. However, T ’s right subtree is balanced.
  • An integer tree is a binary search tree (BST) if for every node in the tree, the value of the node is ≥ all values in its left subtree and ≤ all values in its right subtree. T is not a BST because its left subtree contains a value (C) greater than its root. However, the right subtree of T is a BST.
  • The binary address of a tree node is defined as follows.
    • The binary address of the root of a tree is 1.
    • If the binary address of a node is n, the binary address of its left child is 2n and the binary address of its right child is 2n + 1.

For example, here is a version of T in which each node has been annotated with its binary address:

B 1

C 2 G 3

D 6

E 12 F 13

H 7

  • The pre-order address of a tree node is an integer (starting at 1) that indicates the order in which that node would be visited in a pre-order traversal of the tree. For example, here is a version of T in which each node has been annotated with its pre-order address:

Hint: define labelPreOrderAddress in terms of an auxiliary recursive function that takes two arguments – a tree and a pre-order address – and returns a tree. The OT.size() method is particularly helpful here.

Notes:

  • Flesh out the skeletons for the methods in the class PS6TreeOps.
  • You can use the methods of the ObjectTree class (Appendix A) and the ObjectTreeOps class (Appendix B) using the prefix OT..
  • The invocation java PS6TreeOps method-name tree-string will test the method named method-name on the tree whose string representation is tree-string. For example: [fturbak@wampeter ps6] java PS6TreeOps labelPreOrderAddress "<<* A > B < C >>" labelPreOrderAddress( << A > B < C >> ) = << 2 > 1 < 3 *>> The invocation java PS6TreeOps method-name will run some standard test cases for the method named method-name. The invocation java PS6TreeOps will run standard test cases for all five methods in the problem. You are encouraged to read and understand the testing code and to add any test cases you think are helpful.

Problem 2 [20]: Tree Enumerations In class, we have studied various “orders” for traversing the elements of a binary tree: pre-order, in-order, and post-order. In this problem, we shall extend these traversal notions to enumerating the the elements of a binary tree. It turns out that stacks and queues are very helpful for implementing tree enumerations. Figs. 1–2 present the implementation of a InOrderElts class that enumerates the elements of an ObjectTree according to a depth-first, left-to-right in-order traversal. The class has a single instance variable, stk, that holds a stack of non-empty ObjectTrees that intuitively are “still to be processed”. The main method tests InOrderElts in three different ways, according to the nature of arg in java InOrderElts arg:

  1. If arg is the string representation of a tree, the elements of the tree are displayed in in-order by EnumTest.test. For example:

[cs230@koala ps6] java InOrderElts "<<<* 4 > 1 << 5 > 2 >> 6 < 3 < 7 *>>>"

Enumerating elements of <<<* 4 > 1 << 5 > 2 >> 6 < 3 < 7 *>>> 4 1 5 2 6 3 7

Total number of elements: 7

  1. If arg is a positive integer n, the elements of a breadth-first tree with n nodes labeled with strings (not numbers) 1 through n are displayed in in-order by EnumTest.test. A breadth- first tree with n nodes is a binary tree whose n nodes have the binary addresses 1 through n and in which each node is labeled with its binary address. The binary address of a tree node is defined as follows. - The binary address of the root of a tree is 1. - If the binary address of a node is n, the binary address of its left child is 2n and the binary address of its right child is 2n + 1.

For example, the breadth-first tree with 12 nodes is:

// ****************************** TESTING ******************************

public static void main (String [] args) { testString(args[0]); }

public static void testString (String s) { // If s is an integer n , create a breadth first tree with n elements: try { testTree(OT.breadthTree(1, Integer.parseInt(s))); } catch (NumberFormatException e1) { // Otherwise, try to parse s as a string tree representation try { testTree(OT.fromString(s)); } catch (Exception e2) { // Otherwise treat as the name of a file, // in which each line is a number, tree rep, or filename Enumeration lines = new FileLines(s); while (lines.hasMoreElements()) { testString((String) lines.nextElement()); } } } }

public static void testTree (ObjectTree t) { System.out.println("------------------------------------------------------------"); System.out.println("Enumerating elements of " + t); EnumTest.test(new InOrderElts(t)); }

// Hack for abbreviating ObjectTree and ObjectTreeOps as OT. private static ObjectTreeOps OT;

}

Figure 2: Implementation of InOrderElts, Part 2.

Here is a test case based on this tree: [cs230@koala ps6] java InOrderElts 12


Enumerating elements of <<<<* 8 > 4 < 9 >> 2 << 10 > 5 < 11 >>> 1 <<< 12 *> 6 > 3 < 7 *>>> 8 4 9 2 10 5 11 1 12 6 3 7 Total number of elements: 12

  1. Otherwise, arg is assumed to be the name of a file whose lines are either tree representations, numbers, or other filenames, each of which is processed accordingly. For example, if the file name Atree.txt contains the single line <<<* 4 > 1 << 5 > 2 >> 6 < 3 < 7 *>>> then java InOrderElts Atree.txt has the same behavior as the first of the above examples. In this problem, you are asked to understand how InOrderElts works and to create similar enumerations for other traversal orders.

a. [10]: Understanding InOrderElts In this part, you will show how InOrderElts works in the context of the following tree, which we shall assume is named A^2 : 6

1

4 2

5

Consider the following code: ObjectTree A = ObjectTreeOps.fromString("<<<* 4 > 1 << 5 > 2 >> 6 < 3 < 7 *>>>"); Enumeration e = new InOrderElts(A); while (e.hasMoreElements) { System.out.println(e.nextElement()); } Draw a sequence of “snapshots” of the contents of the stack stk at the beginning of every call to nextElement(). Note that nextElement() is called recursively, and the contents of stk at the beginning of these recursive calls should also be drawn. In your sequence of snapshots, also indicate where a tree value is returned by the enumeration. In this problem, you should draw the elements of a stack from left to right where the leftmost element is the top of the stack and the rightmost element is the bottom of the stack. (^2) Even though the labels look like integers, assume this is an ObjectTree with string values such as "1", "2", etc.

Problem 3 [40]: Mutable BST of Bag Entries Implementation of Bags A bag is a collection of unordered elements that may contain multiple occurrences of each element. In the CS230 collection hierarchy, the Bag interface describes mutable bags. You should study this interface (Appendix D) before proceeding with this problem. In this problem, you will implement a class BagMBSTBagEntries that represents bags as a mutable binary search tree of entries that pair elements in the bag with their number of occurrences. Each entry should be an instance of the following BagEntry class:

public class BagEntry {

public Object elt; public int num;

public BagEntry (Object elt, int num) { this.elt = elt; this.num = num; }

public String toString () { return "BagEntry[" + elt + "," + num + "]"; }

}

To improve the running time of the size() and count() bag operations, the values to be returned by these methods should be cached in instance variables of the BagMBSTEntries class. So instances of BagMBSTEntries should have the following instances variables:

  • comp: a comparator for determining the order of elements.
  • entries: a mutable binary search tree (i.e., an instance of ObjectMTree satisfying the binary search tree property) whose elements are instances of BagEntry.
  • size: the number of element occurrences currently in the bag (includes duplicates).
  • count: the number of distinct elements currently in the bag (does not include duplicates).

For example, Fig. 3 shows one possible representation of an instance of BagMBSTEntries that contains two As, three Bs and one C. (The shape of the tree is determined by the order in which the elements were inserted.)

BagMBSTEntries entries count 3 size 6 comp ... BagEntry elt B num 3

BagEntry elt A num 2

BagEntry elt C num 1

Figure 3: An example of a BagMBSTEntries instance.

To complete this problem, you need to flesh out the following methods of the bag implementation in BagMBSTEntries.java using the representation described above:

Constructor Methods

public BagMBSTEntries (Comparator c); public BagMBSTEntries ();

Instance Methods

public Object choose(); public void clear(); public Object clone(); public int count(); public boolean delete(Object x); public boolean deleteAll(Object x); public Object deleteOne(); public boolean isMember(Object x); public void insert(Object x); public ObjectList toList(); public int occurrences(Object x); public int size();

Note that many instance methods from the Bag interface in Appendix D are missing from the above list. This is because the BagMBSTEntries class inherits implementations of these other methods from its superclasses. Test your implementation by executing java BagMBSTEntries, which invokes the bag methods on various simple BagMBSTEntries instances. Study the output carefully to make sure that the methods behave as expected. You should turn in the transcript of this test for your final version of the code as part of your hardcopy submission.

public class FindEntryInfo {

public ObjectMTree parent, child; public boolean isChildToLeft; public BagEntry entry;

public FindEntryInfo (ObjectMTree parent, ObjectMTree child, boolean isChildToLeft) { this.parent = parent; this.child = child; this.isChildToLeft = isChildToLeft; if (ObjectMTree.isLeaf(child)) { this.entry = null; } else { this.entry = (BagEntry) ObjectMTree.value(child); } } }

Figure 4: The FindEntryInfo class.

import java.util.Comparator;

public class BagEntryComparator implements Comparator {

private Comparator eltComp;

public BagEntryComparator (Comparator eltComp) { this.eltComp = eltComp; }

public int compare (Object x, Object y) { return eltComp.compare(((BagEntry) x).elt, ((BagEntry) y).elt); }

public boolean equals (Object c) { if (c instanceof BagEntryComparator) { return eltComp.equals(((BagEntryComparator) c).eltComp); } else { return false; } } }

Figure 5: The BagEntryComparator class.

Appendix A: ObjectTree Contract

The ObjectTree class models immutable trees whose nodes hold object values.

Public Class Methods:

public static ObjectTree leaf (); Returns a leaf – i.e., a distingushed non-value-bearing node that denotes an empty tree.

public static ObjectTree node (ObjectTree l, Object v, ObjectTree r); Returns a tree node whose left subtree is l, whose value is v, and whose right subtree is r.

public static boolean isLeaf (ObjectTree t); Returns true if t is a leaf and false otherwise (i.e., if t is a tree node).

public static Object value (ObjectTree t); If t is a node, returns the value it holds. If t is a leaf, throws a RuntimeException indicating that a leaf has no value.

public static ObjectTree left (ObjectTree t); If t is a node, returns its left subtree. If t is a leaf, throws a RuntimeException indicating that a leaf has no left subtree.

public static ObjectTree right (ObjectTree t); If t is a node, returns its right subtree. If t is a leaf, throws a RuntimeException indicating that a leaf has no right subtree.

public static String toString (ObjectTree t); Returns the string representation of t (see the description in the toString() instance method).

public static ObjectTree fromString (String s); If s is a string representation of an object tree (see the description in the toString() in- stance method), returns an object tree with string elements whose string representation is s. Otherwise, throws a RuntimeException.

Public Instance Methods:

public String toString (); Returns a string representation of this tree. In this representation, a leaf is represented by

  • and a node N is represented by , where L is the string representation of the left subtree of N, V is the string representation of the value of N, and R is the string representation of the right subtree of N. For example, the tree created via: node(node(leaf(),"A",leaf()), "B", node(node(leaf(),"C",leaf()), "D", leaf())) has the following string representation: "<<* A > B << C *> D *>>"

Appendix C: ObjectMTree Contract

The ObjectMTree class models mutable trees whose nodes hold object values.

Public Class Methods:

public static ObjectMTree leaf (); Returns a leaf – i.e., a distingushed non-value-bearing node that denotes an empty tree.

public static ObjectMTree node (ObjectMTree l, Object v, ObjectMTree r); Returns a tree node whose left subtree is l, whose value is v, and whose right subtree is r.

public static boolean isLeaf (ObjectMTree t); Returns true if t is a leaf and false otherwise (i.e., if t is a tree node).

public static Object value (ObjectMTree t); If t is a node, returns the value it holds. If t is a leaf, throws a RuntimeException indicating that a leaf has no value.

public static ObjectMTree left (ObjectMTree t); If t is a node, returns its left subtree. If t is a leaf, throws a RuntimeException indicating that a leaf has no left subtree.

public static ObjectMTree right (ObjectMTree t); If t is a node, returns its right subtree. If t is a leaf, throws a RuntimeException indicating that a leaf has no right subtree.

public static void setValue (ObjectMTree t, Object newValue); If t is a node, its value is changed to be newValue. If t is a leaf, throws a RuntimeException indicating that a leaf has no value.

public static void setLeft (ObjectMTree t, ObjectMTree newLeft); If t is a node, its left subtree is changed to be newLeft. If t is a leaf, throws a RuntimeException indicating that a leaf has no left subtree.

public static void setRight (ObjectMTree t, ObjectMTree newRight); If t is a node, its right subtree is changed to be newRight. If t is a leaf, throws a RuntimeException indicating that a leaf has no right subtree.

Public Instance Methods:

public String toString (); Returns a string representation of this tree. In this representation, a leaf is represented by

  • and a node N is represented by , where L is the string representation of the left subtree of N, V is the string representation of the value of N, and R is the string representation of the right subtree of N. For example, the tree created via: node(node(leaf(),"A",leaf()), "B", node(node(leaf(),"C",leaf()), "D", leaf())) has the following string representation: "<<* A > B << C *> D *>>"

Appendix D: Bag Interface

The Bag interface describes mutable collections of unordered elements that may contain multiple occurrences of each element. In mathematics, multiset is a synonym for bag. Each bag instance has a Comparator that is used to determine element equality (and may be used in bag implementations to order elements).

Public Instance Methods Inherited from Collection Interface:

public void insert (Object elt); Modifies this bag by inserting a new occurrence of elt.

public Object deleteFirst (); Deletes and returns an arbitrary element of this bag. Throws a RuntimeException if this bag is empty. The deleteFirst method is a synonym for deleteOne.

public Object first (); Returns an arbitrary element of this bag. Throws a RuntimeException if this bag is empty. The first method is a synonym for choose.

public int size (); Returns the number of element occurrences in this bag.

public boolean isEmpty (); Returns true if this bag has no elements, and false otherwise.

public void clear (); Removes all elements from this bag.

public Object clone (); Returns a ”shallow” copy of this bag – i.e. the copied bag structure is new, but elements themselves are shared with the old bag. Operations on the copied bag do not affect the original bag and vice versa. Operations on mutable elements of the copied bag do affect elements of the original bag, and vice versa.

public Enumeration elements (); Returns an enumeration of the element occurrences in this bag in an arbitrary order.

public ObjectList toList (); Returns a list of the element occurrences in this bag in an arbitrary order.

public String name (); Returns a name indicating the implementation of this bag.

Public Instance Methods Inherited from ComparatorCollection Interface:

public Comparator comparator (); Returns the comparator used by this bag to compare elements.

public boolean delete (Object elt); Deletes one occurrence of elt from this bag. Returns true if elt was a member of the bag and false otherwise.

Problem Set Header Page Please make this the first page of your hardcopy submission.

CS230 Problem Set 6

Due 6pm Friday November 12

Names of Team Members:

Date & Time Submitted:

Collaborators (anyone you or your team collaborated with):

By signing below, I/we attest that I/we have followed the collaboration policy

as specified in the Course Information handout.

Signature(s):

In the Time column, please estimate the time you or your team spent on the parts of this problem set. Team members should be working closely together, so it will be assumed that the time reported is the time for each team member. Please try to be as accurate as possible; this information will help me design future problem sets. I will fill out the Score column when grading your problem set.

Part Time Score

General Reading

Problem 1 [40]

Problem 2 [20]

Problem 3 [40]

Total