SlideShare a Scribd company logo
META-INF/MANIFEST.MF
Manifest-Version: 1.0
.classpath
PriorityQueue.classpublicsynchronizedclass PriorityQueue {
Heap q;
public void PriorityQueue(int, java.util.Comparator);
public Object peek();
public Object remove();
void add(Object);
boolean isEmpty();
public int size();
}
PriorityQueue.javaPriorityQueue.javaimport java.util.Comparat
or;
publicclassPriorityQueue<E>{
Heap q;
/**
*PriorityQueue initializes the queue.
*
* @param initialCapacity an int that is the heaps initial size.
* @param comparator the priority of various imputs.
*/
publicPriorityQueue(int initialCapacity,Comparator<?super E>
comparator){
q=newHeap(initialCapacity,comparator);
}
/**
* Peek, returns the next item in the queue without removing
it.
*
* If it is empty then null is returned.
* @return the next item in the queue.
*/
public E peek(){
if(q.size()==0){
returnnull;
}
return(E) q.findMax();
}
/**
* This removes the first item from the queue.
*
* It returns null if the queue is empty.
* @return the first item in the queue.
*/
public E remove(){
if(q.size()==0){
returnnull;
}
return(E) q.removeMax();
}
/**
* This adds item to the queue
* @param item that is added to the queue.
*/
void add(E item){
q.insert(item);
}
/**
* isEmpty returns if the queue is empty or not.
*
* @return boolean if the queue is empty or not.
*/
boolean isEmpty(){
if(q.size()!=0){
returnfalse;
}
returntrue;
}
/**
* size returns the size of the queue.
*
* @return int the size of the queue.
*/
publicint size(){
return q.size();
}
}
ArithmeticExpression.classpublicsynchronizedclass
ArithmeticExpression {
BinaryTree t;
java.util.ArrayList list;
String equation;
void ArithmeticExpression(String) throws
java.text.ParseException;
public String toString(BinaryTree);
public String toPostfixString(BinaryTree);
void setVariable(String, int) throws
java.rmi.NotBoundException;
public int evaluate(BinaryTree);
}
ArithmeticExpression.javaArithmeticExpression.javaimport java
.rmi.NotBoundException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Stack;
/**
* ArithmeticExpression takes equations in the form of strings c
reates a binary
* tree, and can return either the regular or postfix equation. It a
lso allows
* them to be calculated.
*
*
* Extra Credit:
* ** it can handle spaces or no spaces in the string inputted. **
it can return
* regular or postfix notation
*
* @author tai-lanhirabayashi
*
*/
publicclassArithmeticExpression{
BinaryTree t;
ArrayList list;
String equation;
/**
* ArithmeticExpression is the construction which takes in a
space
* delimitated equation containing "*,/,+,-
" symbols and converts it into a
* binary tree.
*
* If the expression is not valid it will throw a ParseExceptio
n. This is
* the constructor. It will take a String containing the express
ion.
*
* ** The equation can take in stings delimitated by spaces, o
r withot any
* spaces. If it contains a mix, then the non spaced part(s) wil
l be
* considered to be a variable.
*
* @param expression
* @throws ParseException
* if the string is not a valid equation
*/
@SuppressWarnings({"unchecked","rawtypes"})
ArithmeticExpression(String expression)throwsParseException{
//hold the string globally
equation = expression;
//create a new arrayList to be used globally that holds the variab
les
list =newArrayList();
//split the string
String[] s = expression.split(" ");
// create a stack of tree's and operators
Stack tree =newStack();
Stack operator =newStack();
//create the string Next
String next ="";
// if the string expression doesnt contain spaces
if(!expression.contains(" ")){
int i =0;
//if it starts with an operator throw an error this cannot be.
if(expression.charAt(0)=='+'|| expression.charAt(0)=='*'
|| expression.charAt(0)=='-'
|| expression.charAt(0)=='/'){
System.out.println("this equation starts with a operator.");
thrownewParseException(expression,0);
}
// if the expression ends with an operator throw an error this can
not be.
if(expression.charAt(expression.length()-1)=='+'
|| expression.charAt(expression.length()-1)=='*'
|| expression.charAt(expression.length()-1)=='-'
|| expression.charAt(expression.length()-1)=='/'){
System.out.println("this equation ends with a operator.");
thrownewParseException(expression, expression.length());
}
//go through each characer in the expression and see if its a num
ber/variable, or operator.
while(i < expression.length()){
if(expression.charAt(i)=='+'|| expression.charAt(i)=='*'
|| expression.charAt(i)=='-'
|| expression.charAt(i)=='/'){
// if the character is a operator add a space to the begining and f
ront and add it to the "next" string
String str =String.valueOf(expression.charAt(i));
next = next +" "+ str +" ";
}else{
// if its an operator add it to the end of the "next" string.
next = next + expression.charAt(i);
}
// increase i to move to the next character.
i++;
}
// split the new string with added spaces.
s = next.split(" ");
}
// if the string still doesnt exist throw the error.
if(s.length ==0){
System.out
.println("there has been an error. You have not entered a string
with any characters");
thrownewParseException(expression,0);
}
// make sure there arent two operators in a row.
for(int i =0; i < s.length; i++){
if(i >=1
&&(s[i].equals("+")|| s[i].equals("-")
|| s[i].equals("*")|| s[i].equals("/"))){
if(s[i -1].equals("+")|| s[i -1].equals("-")
|| s[i -1].equals("*")|| s[i -1].equals("/")){
System.out
.println("there were two operators in a row. The equation is not
valid.");
thrownewParseException(expression, i);
}
}
// check to make sure there arent two operands in a row in the St
ring[]
if(i >=1
&&(s[i].equals("+")==false&& s[i].equals("-")==false
&& s[i].equals("*")==false&& s[i].equals("/")==false)){
if(s[i -1].equals("+")==false
&& s[i -1].equals("-")==false
&& s[i -1].equals("*")==false
&& s[i -1].equals("/")==false){
System.out
.println("there were two operands in a row. The equation is not
valid.");
thrownewParseException(expression, i);
}
}
// if its a number create a new tree node, and add it to the tree st
ack
if(s[i].equals("+")==false&& s[i].equals("-")==false
&& s[i].equals("*")==false&& s[i].equals("/")==false){
BinaryTree o =newBinaryTree(null, s[i],null);
tree.add(o);
}elseif(operator.empty()|| s[i].equals("*")|| s[i].equals("/")){
//if its a * or / symbol hold it to ensure order of operation
operator.push(s[i]);
}else{
//group the tree's together.
while(operator.empty()==false){
String operatorHeld =(String) operator.pop();
BinaryTree one =(BinaryTree) tree.pop();
BinaryTree two =(BinaryTree) tree.pop();
BinaryTree n =newBinaryTree(one, operatorHeld, two);
tree.push(n);
}
operator.push(s[i]);
}
}
// at the end ensure that the operator is empty.
while(operator.empty()==false){
String operatorHeld =(String) operator.pop();
BinaryTree one =(BinaryTree) tree.pop();
BinaryTree two =(BinaryTree) tree.pop();
BinaryTree n =newBinaryTree(one, operatorHeld, two);
tree.push(n);
}
//if there is more than 1 tree at the end something went wrong
// this should not occur as it should have been caught earlier
// this is just to ensure completeness.
if(tree.size()>=2){
System.out
.println("this expression is invalid. There were more operands t
han operators.");
System.out
.println("this should not occur it should have been caught earlie
r");
while(tree.empty()==false){
return;
}
}
//if there are still operators there is something wrong
// this should not occur as it should have been caught earlier
// this is just to ensure completeness.
if(operator.empty()==false){
System.out
.println("this should not occur it should have been caught earlie
r.");
System.out
.println("there were too many operators in the string the progra
m cannot continue.");
{
return;
}
}
// set the tree globally
t =(BinaryTree) tree.pop();
}
/**
* toString returns the String equation of that the passed in bi
nary tree
* represents.
*
* @param tree
* that represents an equation
* @return the String that is represented by the passed in Bin
aryTree.
*/
@SuppressWarnings("rawtypes")
publicString toString(BinaryTree tree){
// if its a leaf return its value
if(tree.isLeaf()==true){
return(String) tree.getValue();
}else{
//else combine each parent child combination
//call recursively, and contain each call in parenthesis.
String s =("("+ toString(tree.getLeftChild())+ tree.getValue()
+ toString(tree.getRightChild())+")");
return s;
}
}
/**
* toPostfixString returns the string containing the parsed exp
ression in
* postFix notation with spaces between numbers and operato
rs to ensure clarity.
*
* @param tree that represents an equation
* @return the String that is represented by the passed in Bin
aryTree in
* postfix form.
*/
@SuppressWarnings("unchecked")
publicString toPostfixString(BinaryTree tree){
//if its a leaf return its value
if(tree.isLeaf()==true){
return(String) tree.getValue();
}else{
//otherwise call recursively down the tree
// and add the operator to the end of the two operands.
// also add spaces to allow numbers to be seen individually.
String s = toPostfixString(tree.getRightChild())+" "
+ toPostfixString(tree.getLeftChild())+" "
+ tree.getValue();
System.out.println("this is what s is "+ s);
return s;
}
}
/**
* This allows the user to set a value for a variable in the exp
ression. If
* the variable does not exist in the function, throw a NotBou
ndException.
*
* @param name of the variable
* @param value that the variable has
* @throws NotBoundException if the variable is not used in
the equation
*/
void setVariable(String name,int value)throwsNotBoundExcepti
on{
//Note var, is not a Var it is a seperate class that is an object.
//if the equation string doesnt contain the variable throw an erro
r
if(!equation.contains(name)){
thrownewNotBoundException();
}
// else continue and check if the var object is already in the list
for(int i =0; i < list.size(); i++){
var v =(var) list.get(i);
if(v.getName().equals(name)){
//if so change the value of the var object
v.setValue(value);
return;
}
}
// otherwise add the var object to the list.
list.add(new var(name, value));
}
/**
* Evaluate returns the integer result of the expression.
*
* Variables that are not declared are calculated at 0.
*
* @return the value of the equation
*/
@SuppressWarnings("unused")
publicint evaluate(BinaryTree tree){
//if it is a leaf
if(tree.isLeaf()==true){
String s =(String) tree.getValue();
//if all characters are numbers simply skip down to return the in
teger value.
for(int i =0; i < s.length(); i++){
if(s.charAt(i)=='0'|| s.charAt(i)==('1')
|| s.charAt(i)=='2'|| s.charAt(i)=='3'
|| s.charAt(i)=='4'|| s.charAt(i)=='5'
|| s.charAt(i)=='6'|| s.charAt(i)=='7'
|| s.charAt(i)=='8'|| s.charAt(i)=='9'){
}else{
//if there are non numeric characters check if the list has their v
alues
for(int j =0; j < list.size(); j++){
var h =(var) list.get(j);
if(h.getName().equals(s)){
return h.getValue();
}
}
//otherwise tell the user that this variable cannot be found and t
hat its value is calulated at 0
System.out.println("this variable "+ s
+" cannot be found! Its value will be 0.");
return0;
}
returnInteger.parseInt((String) tree.getValue());
}
}
//find the left and right values of the tree
int left = evaluate(tree.getLeftChild());
int right = evaluate(tree.getRightChild());
//calculate appropriately.
if(tree.getValue().equals("*")){
return left * right;
}elseif(tree.getValue().equals("/")){
return left / right;
}elseif(tree.getValue().equals("+")){
return left + right;
}
return left - right;
}
}
Map.classpublicsynchronizedclass Map {
BSTMap root;
BSTMap found;
java.util.TreeSet set;
public void Map();
public void put(Comparable, Object);
public Object get(Comparable);
public boolean containsKey(Comparable);
private BSTMap getBSTMap(Comparable);
public Object remove(Comparable);
private BSTMap sucessor(BSTMap);
public java.util.Set keySet();
}
Map.javaMap.javaimport java.util.Set;
import java.util.TreeSet;
publicclassMap<K extendsComparable<K>,V>{
BSTMap root;
BSTMap found;
TreeSet<K> set;
/**
* Map initializes the map.
*/
publicMap(){
set=newTreeSet<K>();
root=null;
found=null;
}
/**
* put loads the Key and value into a BSTMap object, and the
key into the set.
*
* If the key already exists the value is changed to the new va
lue.
* @param key the K key value
* @param value the V value value
*/
publicvoid put(K key, V value){
//if the root is null this is the root
if(root==null){
root=newBSTMap(key,value);
set.add(key);
//if the key exists then change the value
}elseif(get(key)!=null){
getBSTMap(key).obj.value=value;
}else{
//otherwise create a new BSTMap
BSTMap i =newBSTMap(key,value);
//add it to the set
set.add(key);
//and find its place in the BSTmap tree.No key can be identical.
boolean done=false;
BSTMap c= root;
while(done==false){
//if it is bigger go right
if(key.compareTo((K) c.obj.getKey())>=0){
if(c.getRight()==null){
c.setRight(i);
done=true;
}else{
c=c.getRight();
}
//if it is smaller go left.
}elseif(key.compareTo((K) c.obj.getKey())<0){
if(c.getLeft()==null){
c.setLeft(i);
done=true;
}else{
c=c.getLeft();
}
}
}
}
}
/**
* This finds the value associated with they key. If this key c
annot be found null is returned.
* @param key the K key value
* @return V the associated V value.
*/
public V get(K key){
BSTMap current= root;
if(root==null){
returnnull;
}
while(current!=null&& current.obj.getKey().equals(key)==false
){
if(key.compareTo((K) current.obj.getKey())<0){
current=current.getLeft();
}else{
current=current.getRight();
}
}
if(current==null){
returnnull;
}
if(current.obj.getKey().equals(key)){
return(V) current.obj.getValue();
}
returnnull;
}
/**
*containsKey returns boolean if the key exists in the map.
* @param key the K key value to look for
* @return boolean if it exists
*/
publicboolean containsKey(K key){
BSTMap current= root;
if(root==null){
returnfalse;
}
while(current!=null&& current.obj.getKey().equals(key)==false
){
if(key.compareTo((K) current.obj.getKey())<0){
current=current.getLeft();
}else{
current=current.getRight();
}
}
if(current==null){
returnfalse;
}
return current.obj.getKey().equals(key);
}
/**
* getBSTMap returns the BSTMap associated with a key val
ue
* @param key the K key value
* @return BSTMap contained the K key.
*/
privateBSTMap getBSTMap(K key){
BSTMap current= root;
if(root==null){
returnnull;
}
while(current!=null&& current.obj.getKey().equals(key)==false
){
if(key.compareTo((K) current.obj.getKey())<0){
current=current.getLeft();
}else{
current=current.getRight();
}
}
if(current.obj.getKey().equals(key)){
return current;
}
returnnull;
}
/**
* remove removes the BSTMap associated with they key, an
d returns its associated value.
*
* If the key cannot be found null is returned
* @param key the K key value to be found
* @return V the value of associated with the BSTMap contai
ning the K key value.
*/
public V remove(K key){
if(root==null){
returnnull;
}elseif(root.obj.getKey().equals(key)){
System.out.println("the node to remove is the root.");
V val=(V) root.obj.getValue();
if(root.isLeaf()){
root=null;
}elseif(root.getLeft()==null){
root=root.getRight();
}elseif(root.getRight()==null){
root=root.getLeft();
}else{
root=sucessor(root);
}
return val;
}
BSTMap n= getBSTMap(key);
if(n==null){
returnnull;
}else{
set.remove(key);
V a=(V) n.obj.getValue();
BSTMap temp=null;
BSTMap child=null;
if(n.isLeaf()){
temp=n;
n=null;
}elseif(n.getLeft()!=null&& n.getLeft().getRight()==null){
temp=n;
n.getLeft().setRight(n.right);
n.setLeft(null);
}elseif(n.getRight()!=null&& n.getRight().getLeft()==null){
temp=n;
n.getRight().setLeft(n.getLeft());
n.setRight(null);
}else{
temp=sucessor(n);
n.setRight(null);
}
System.out.println("this is the temp:"+
temp.obj.key);
if(temp.getLeft()!=null){
child=temp.getLeft();
}else{
child=temp.getRight();
}if(child!=null){
child.parent=temp.parent;
}if(temp.parent.getLeft()==temp){
temp.parent.setLeft(child);
}else{
temp.parent.setRight(child);
}
return a;
}
}
privateBSTMap sucessor(BSTMap n){
boolean running=true;
BSTMap current=n.getRight();
while(running){
if(current.getLeft()!=null){
current=current.getLeft();
}else{
running=false;
}
}
return current;
}
/**
* keySet returns a Set of the K key values in the map.
* @return
*/
publicSet<K> keySet(){
return set;
}
}
BinaryTree.classpublicsynchronizedclass BinaryTree {
Object v;
BinaryTree treeLeft;
BinaryTree treeRight;
void BinaryTree(BinaryTree, Object, BinaryTree);
BinaryTree getLeftChild();
BinaryTree getRightChild();
void setLeftChild(BinaryTree);
void setRightChild(BinaryTree);
void setValue(Object);
Object getValue();
boolean isLeaf();
}
BinaryTree.javaBinaryTree.java
/**
* BinaryTree is a form of linked nodes that form a tree.
*
* @author tai-lan hirabayashi
*
* @param <E> the object value that is within each node.
*/
publicclassBinaryTree<E>{
E v;
BinaryTree<E> treeLeft;
BinaryTree<E> treeRight;
/**
* BinaryTree creates a new node binaryTree which holds an
object value.
* It takes in the value, left and right child and holds them wi
thin the node.
* @param left the left child of the node.
* @param value the object the node holds
* @param right the right child of the node
*/
BinaryTree(BinaryTree<E> left, E value,BinaryTree<E> right){
v=value;
treeLeft=left;
treeRight=right;
}
/**
* getLeftChild returns the left child node.
* @return the left child, a binary tree node.
*/
BinaryTree<E> getLeftChild(){
return treeLeft;
}
/**
* getRightChild returns the right child node.
* @return the right child,a binaryTree node.
*/
BinaryTree<E> getRightChild(){
return treeRight;
}
/**
* setLeftChild, sets the left child of the current node.
* @param l is the left child, a binaryTree node.
*/
void setLeftChild(BinaryTree<E> l){
treeLeft=l;
}
/**
* setRightChild, sets the right child of the current node.
* @param r the right child, a binaryTree node.
*/
void setRightChild(BinaryTree<E> r){
treeRight=r;
}
/**
* setValue sets the value of a node.
* @param object value of the node.
*/
void setValue(E object){
v=object;
}
/**
* getValue returns the value held in the node.
* @return the object value of the node.
*/
E getValue(){
return v;
}
/**
* isLeaf checks if the node is a leaf node by checking if it ha
s children.
* @return boolean if the node is a leaf node.
*/
boolean isLeaf(){
if(getLeftChild()==null&& getRightChild()==null){
returntrue;
}
returnfalse;
}
}
HuffmanTreeTest.classpublicsynchronizedclass
HuffmanTreeTest {
HuffmanTree h;
String t;
public void HuffmanTreeTest();
public void start() throws java.io.FileNotFoundException;
public void testEncode();
public void testDecode();
}
HuffmanTreeTest.javaHuffmanTreeTest.java
importstatic org.junit.Assert.*;
import java.io.File;
import java.io.FileNotFoundException;
import org.junit.Before;
import org.junit.Test;
publicclassHuffmanTreeTest{
HuffmanTree h;
String t;
/**
* start creates a test case
* @throws FileNotFoundException
*/
@Before
publicvoid start()throwsFileNotFoundException{
h =HuffmanTree.newTreeFromFile(newFile("/Users/tai-
lanhirabayashi/Desktop/test.txt"));
}
/**
* testEncode tries to encode a string.
*/
@Test
publicvoid testEncode(){
t = h.encode("This program must work!");
}
/**
* testDecode tries to decode the string.
*/
@Test
publicvoid testDecode(){
assertEquals("This program must work!", h.decode(t));
}
}
HTreeTest.classpublicsynchronizedclass HTreeTest {
HTree t;
public void HTreeTest();
public void start();
public void testGetBelow();
public void testGetF();
public void testGetS();
public void testGetL();
public void testGetR();
public void testIsLeaf();
public void testSetL();
public void testSetR();
}
HTreeTest.javaHTreeTest.javaimportstatic org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
publicclassHTreeTest{
HTree t;
/**
* Start initializes a test case of HTree
*/
@Before
publicvoid start(){
t=newHTree(1,"one");
HTree a=newHTree(2,"two");
HTree b=newHTree(3,"three");
t.setL(a);
t.setR(b);
}
/**
* testGetBelow tests GetBelow
*/
@Test
publicvoid testGetBelow(){
assertEquals(1,t.getBelow());
assertEquals(0,t.getL().getBelow());
HTree a=newHTree(4,"a");
HTree b=newHTree(5,"b");
t.getL().setL(a);
t.getL().setR(b);
assertEquals(2,t.getBelow());
}
/**
* testGetF tests getF
*/
@Test
publicvoid testGetF(){
assertEquals(1,t.getF());
assertEquals(2,t.getL().getF());
assertEquals(3,t.getR().getF());
}
/**
* testGetS tests getS
*/
@Test
publicvoid testGetS(){
assertEquals("one",t.getS());
assertEquals("two",t.getL().getS());
assertEquals("three",t.getR().getS());
}
/**
* testGetL tests getL
*/
@Test
publicvoid testGetL(){
assertEquals(2,t.getL().getF());
assertEquals(null,t.getL().getL());
}
/**
* testGetR tests getR
*/
@Test
publicvoid testGetR(){
assertEquals(3,t.getR().getF());
assertEquals(null,t.getR().getR());
}
/**
* testIsLeaf tests isLeaf
*/
@Test
publicvoid testIsLeaf(){
assertEquals(false,t.isLeaf());
assertEquals(true,t.getR().isLeaf());
assertEquals(true,t.getL().isLeaf());
}
/**
* testSetL tests setL
*/
@Test
publicvoid testSetL(){
assertEquals(2,t.getL().getF());
t.setL(null);
assertEquals(null,t.getL());
}
/**
* testSetR tests setR
*/
@Test
publicvoid testSetR(){
assertEquals(3,t.getR().getF());
t.setR(null);
assertEquals(null,t.getR());
}
}
Heap$MaxHeapComparator.classpublicsynchronizedclass
Heap$MaxHeapComparator implements java.util.Comparator {
public void Heap$MaxHeapComparator();
public int compare(Comparable, Comparable);
}
Heap$MinHeapComparator.classpublicsynchronizedclass
Heap$MinHeapComparator implements java.util.Comparator {
public void Heap$MinHeapComparator();
public int compare(Comparable, Comparable);
}
Heap.classpublicsynchronizedclass Heap {
int s;
Object[] h;
int maxS;
java.util.Comparator c;
public void Heap(int, java.util.Comparator);
public Object findMax();
public Object removeMax();
public void insert(Object);
public int size();
private void siftUp(int);
private void siftDown(int);
}
Heap.javaHeap.javaimport java.lang.reflect.Array;
import java.util.Comparator;
import java.util.NoSuchElementException;
publicclassHeap<E>{
int s;
Object[] h;
int maxS;
Comparator c;
/**
* Heap takes in the initial size of the heap.
* @param i the integer value of the size of the heap.
*/
publicHeap(int i,Comparator<?super E> comparator){
c=comparator;
s=0;
maxS=i;
h=newObject[i];
}
/**
* findMax returns the largest item of the heap.
* If the heap is empty it will throw a noSuchElementExcepti
on.
* @return E the max object
*/
public E findMax(){
if(s==0){
System.out.println("an error has been thrown because the heap i
s empty");
thrownewNoSuchElementException();
}
return(E) h[0];
}
/**
* removeMax removes the largest item. If the list is empty a
NoSuchElementException is thrown.
* @return the max object
*/
public E removeMax(){
if(s==0){
System.out.println("an error has been thrown because the heap i
s empty");
thrownewNoSuchElementException();
}
E last =(E) h[s-1];
E first =(E) h[0];
h[0]=last;
h[s-1]=null;
s--;
siftDown(0);
return first;
}
/**
* insert inserts an item into the heap and bubbles it into the
correct position.
* @param item that is inserted
*/
publicvoid insert(E item){
if(s==maxS-1){
maxS=maxS*2;
Object[] grownArray =newObject[maxS];
System.arraycopy(h,0, grownArray,0, h.length);
h=grownArray;
}
h[s]=item;
siftUp(s);
s++;
}
/**
* size returns the size of the heap.
* @return the integer size of the heap
*/
publicint size(){
return s;
}
/**
* siftUp, sifts the node at index i up through the heap into th
e correct position.
* @param i the value to begin sifting
*/
privatevoid siftUp(int i)
{
int n=i;
boolean inPlace =false;
if(n==0){
inPlace=true;
}
while(inPlace==false){
int a=(n-1)/2;
E below=(E) h[n];
E above=(E) h[a];
if(c.compare(below,above)>0){
h[n]= above;
h[a]=below;
n=a;
}else{
inPlace=true;
}
}
}
/**
* SiftDown sifts the node at index i down to the correct spot
in the heap.
* @param i the value to begin sifting
*/
privatevoid siftDown(int i)
{
int n=i;
boolean inPlace =false;
while(inPlace==false){
int a=(n*2)+1;
E above=(E) h[n];
E belowL=(E) h[a];
E belowR=(E) h[a+1];
if(belowL==null&& belowR==null){
return;
}
//if neither of the children are null
if(belowL !=null&& belowR !=null){
//compare to the left child
if(c.compare(above,belowL)<0&& c.compare(belowL,belowR)>
=0){
System.out.println("down and to the left!");
h[a]= above;
h[n]=belowL;
n=a;
//compare to the right child
}elseif(c.compare(above,belowR)<0){
System.out.println("down and to the right!");
h[a+1]= above;
h[n]=belowR;
n=a;
//otherwise its in place
}else{
System.out.println("its down in place");
inPlace=true;
}
//if the left child isnt null
}elseif(belowL !=null){
if(c.compare(above, belowL)<0){
h[n]= above;
h[a]=belowL;
n=a;
}else{
inPlace=true;
}
}else{
// if the right child isnt null compare it to the parent
if(c.compare(above,belowR)<0){
h[a+1]= above;
h[n]=belowR;
n=a;
}else{
inPlace=true;
}
}
}
}
/**
* MaxHeapComparator compares two values and prioritizes t
he max value.
* @author tai-lanhirabayashi
*
* @param <E> the comparable object
*/
publicstaticclassMaxHeapComparator<E extendsComparable<E
>>implementsComparator<E>{
@Override
publicint compare(E o1, E o2){
return o1.compareTo(o2);
}
}
/**
* MinHeapComparator compares two values and prioritizes t
he lower value
* @author tai-lanhirabayashi
*
* @param <E> the comparable object
*/
publicstaticclassMinHeapComparator<E extendsComparable<E>
>implementsComparator<E>{
@Override
publicint compare(E o1, E o2){
return(-1* o1.compareTo(o2));
}
}
}
PriorityQueueTest.classpublicsynchronizedclass
PriorityQueueTest {
PriorityQueue p;
public void PriorityQueueTest();
public void start();
public void testPeek();
public void testRemove();
public void testSize();
public void testEmpty();
}
PriorityQueueTest.javaPriorityQueueTest.javaimportstatic org.j
unit.Assert.*;
import java.util.Comparator;
import org.junit.Before;
import org.junit.Test;
publicclassPriorityQueueTest{
PriorityQueue p;
/**
* Start initialized the program, with a queue of 1,2,3,4 and a
max priority.
*/
@Before
publicvoid start(){
Comparator<Integer> c =newHeap.MaxHeapComparator();
p=newPriorityQueue(10, c);
p.add(1);
p.add(2);
p.add(3);
p.add(4);
}
/**
* testPeek tests the peek function.
*/
@Test
publicvoid testPeek(){
assertEquals(4, p.peek());
p.remove();
assertEquals(3, p.peek());
p.remove();
assertEquals(2, p.peek());
p.remove();
assertEquals(1, p.peek());
p.remove();
assertEquals(null, p.peek());
}
/**
* restRemove tests the remove function.
*/
@Test
publicvoid testRemove(){
assertEquals(4, p.remove());
assertEquals(3, p.remove());
assertEquals(2, p.remove());
assertEquals(1, p.remove());
assertEquals(null, p.remove());
}
/**
* testSize tests the size function.
*/
@Test
publicvoid testSize(){
assertEquals(4, p.size());
p.remove();
assertEquals(3, p.size());
p.remove();
assertEquals(2, p.size());
p.remove();
assertEquals(1, p.size());
p.remove();
assertEquals(0, p.size());
p.add(9);
assertEquals(1, p.size());
}
/**
* testEmpty tests the isEmpty function of priorityQueue.
*/
@Test
publicvoid testEmpty(){
assertFalse(p.isEmpty());
p.remove();
assertFalse(p.isEmpty());
p.remove();
assertFalse(p.isEmpty());
p.remove();
assertFalse(p.isEmpty());
p.remove();
assertTrue(p.isEmpty());
p.add(5);
assertFalse(p.isEmpty());
}
}
BSTMap.classpublicsynchronizedclass BSTMap extends Map {
nObject obj;
BSTMap left;
BSTMap right;
int s;
BSTMap parent;
public void BSTMap(Object, Object);
public void setParent(BSTMap);
public BSTMap getParent();
public void setLeft(BSTMap);
public void setRight(BSTMap);
public BSTMap getLeft();
public BSTMap getRight();
boolean isLeaf();
}
BSTMap.javaBSTMap.java
publicclassBSTMap<K,V>extendsMap{
nObject obj;
BSTMap<K,V> left;
BSTMap<K,V> right;
int s;
BSTMap<K,V> parent;
/**
* BSTMap creates a node with a K key and V value.
* @param ke the K value
* @param va the V value
*/
publicBSTMap(K ke, V va){
obj=new nObject(ke,va);
left=null;
right=null;
parent=null;
}
/**
* setParent sets the BSTMap which is this nodes parent.
* @param p the parent
*/
publicvoid setParent(BSTMap<K,V> p){
parent=p;
}
/**
* getParent returns the parent of this node.
* @return BSTMap that is this nodes parent.
*/
publicBSTMap<K,V> getParent(){
return parent;
}
/**
* setLeft sets the BSTMap left child.
*
* @param child BSTMap that is this nodes child.
*/
publicvoid setLeft(BSTMap<K,V> child){
left=child;
if(child!=null){
left.setParent(this);
}
}
/**
* setRight sets the this nodes BSTMap child.
* @param child BSTMap that is this nodes child.
*/
publicvoid setRight(BSTMap<K,V> child){
right=child;
if(child!=null){
right.setParent(this);
}
}
/**
* getLeft returns this nodes left BSTMap child.
* @return BSTMap this nodes left child
*/
publicBSTMap<K,V> getLeft(){
return left;
}
/**
* getRight returns this nodes right BSTMap child.
* @return BSTMap this nodes right child
*/
publicBSTMap<K,V> getRight(){
return right;
}
/**
* isLeaf checks if the node is a leaf node by checking if it ha
s children.
*
* It returns true for leaf, false for if it has children.
* @return boolean if the node is a leaf node.
*/
boolean isLeaf(){
if(getLeft()==null&& getRight()==null){
returntrue;
}
returnfalse;
}
}
BinaryTreeTest.classpublicsynchronizedclass BinaryTreeTest {
BinaryTree t;
public void BinaryTreeTest();
public void before();
public void testSetup();
public void testGetLeft();
public void testGetRight();
public void isLeaf();
public void setLeft();
public void setRight();
public void setValue();
}
BinaryTreeTest.javaBinaryTreeTest.javaimportstatic org.junit.A
ssert.*;
import org.junit.Before;
import org.junit.Test;
/**
* BinaryTreeTest tests to see if Binary Tree functions as expect
ed.
* @author tai-lanhirabayashi
*
*/
publicclassBinaryTreeTest{
BinaryTree t;
/**
* before sets up a base case.
*/
@Before
publicvoid before(){
t=newBinaryTree(null,"head",null);
t.setLeftChild(newBinaryTree(null,"second",null));
t.getLeftChild().setLeftChild(newBinaryTree(null,"third",
null));
}
/**
* testSetup makes sure the test has been initialized.
*/
@Test
publicvoid testSetup(){
assertEquals(t.getValue(),"head");
}
/**
* tests the getLeft function
*/
@Test
publicvoid testGetLeft(){
assertEquals(t.getLeftChild().getValue(),"second");
}
/**
* Tests the get right function
*/
@Test
publicvoid testGetRight(){
assertEquals(t.getRightChild(),null);
}
/**
* Tests the isLeaf function.
*/
@Test
publicvoid isLeaf(){
assertEquals(t.getLeftChild().getLeftChild().isLeaf(),true);
}
/**
* Tests the setLeft function
*/
@SuppressWarnings("unchecked")
@Test
publicvoid setLeft(){
t.setLeftChild(newBinaryTree(null,"replace",null));
assertEquals(t.getLeftChild().getValue(),"replace");
}
/**
* tests the setRightChild function
*/
@SuppressWarnings("unchecked")
@Test
publicvoid setRight(){
t.setRightChild(newBinaryTree(null,"right",null));
assertEquals(t.getRightChild().getValue(),"right");
}
/**
* Tests the setValue function.
*/
@Test
publicvoid setValue(){
t.getLeftChild().setValue("reset");
assertEquals(t.getLeftChild().getValue(),"reset");
}
}
ArithmeticExpressionTest.classpublicsynchronizedclass
ArithmeticExpressionTest {
ArithmeticExpression a;
public void ArithmeticExpressionTest();
public void startUp() throws java.text.ParseException;
public void testExceptions();
public void testToString();
public void testEval();
public void testVar() throws java.rmi.NotBoundException,
java.text.ParseException;
public void testPostFix();
public void testWithoutSpaces() throws
java.text.ParseException;
}
ArithmeticExpressionTest.javaArithmeticExpressionTest.javaim
portstatic org.junit.Assert.*;
import java.rmi.NotBoundException;
import java.text.ParseException;
import org.junit.Before;
import org.junit.Test;
/**
* ArithmeticExpressionTest tests the functionality of Arithmeti
cExpression.
*** Note, the Program includes postFix() which returns a postfi
x String of the equation.
*** It can also handle strings with or without spaces.
*
*
* @author tai-lan hirabayashi
*
*/
publicclassArithmeticExpressionTest{
ArithmeticExpression a;
/**
* StartUp sets up the base case scenario.
* @throws ParseException if the equation is not valid.
*/
@Before
publicvoid startUp()throwsParseException{
a=newArithmeticExpression("3 + 4 * 2");
}
/**
* testExceptions tests the programs thrown exceptions.
*/
@Test
publicvoid testExceptions(){
boolean errorThrown =false;
try{
a=newArithmeticExpression("3 + * 2");
}catch(ParseException e){
errorThrown=true;
}
assert(errorThrown);
errorThrown=false;
try{
a.setVariable("y",2);
}catch(NotBoundException e){
errorThrown=true;
}
assert(errorThrown);
}
/**
* testToString tests the toString method of the ArithmeticEx
pression
*/
@Test
publicvoid testToString(){
System.out.println("this is toString: "+ a.toString(a.t));
assertEquals(a.toString(a.t),"((2*4)+3)");
}
/**
* testEval tests the evaluate method of ArithmeticExpression
*/
@Test
publicvoid testEval(){
assertEquals(a.evaluate(a.t),11);
}
/**
* testVar tests the setVariable function of ArithmeticExpress
ion
* by checking how a variable is handled.
* @throws NotBoundException
* @throws ParseException if the equation is not valid.
*/
@Test
publicvoid testVar()throwsNotBoundException,ParseException{
a=newArithmeticExpression("2 + 3 * x");
assertEquals(a.evaluate(a.t),2);
a.setVariable("x",2);
assertEquals(a.evaluate(a.t),8);
}
/**
* Tests the postFix() method.
*/
@Test
publicvoid testPostFix(){
assertEquals(a.toPostfixString(a.t),"3 4 2 * +");
}
@Test
publicvoid testWithoutSpaces()throwsParseException{
a=newArithmeticExpression("2+3*x");
assertEquals(a.evaluate(a.t),2);
}
}
nObject.classpublicsynchronizedclass nObject {
Object key;
Object value;
public void nObject(Object, Object);
public Object getKey();
public Object getValue();
public void changeKey(Object);
public void changeValue(Object);
}
nObject.javanObject.java
publicclass nObject<K,V>{
K key;
V value;
/**
* nObject creates a new nObject object with a K,V values he
ld.
* @param ky the K key value
* @param val the V value value.
*/
public nObject (K ky, V val){
key=ky;
value=val;
}
/**
* getKey returns the K key.
* @return K, the key
*/
public K getKey(){
return key;
}
/**
* getValue returns the V value.
* @return V value
*/
public V getValue(){
return value;
}
/**
* changeK allows the user to pass in a new K key.
* @param ky K to be changed to.
*/
publicvoid changeKey(K ky){
key=ky;
}
/**
* changeValue allows the value to be changed.
* @param val the new V value.
*/
publicvoid changeValue(V val){
value=val;
}
}
BSTMapTest.classpublicsynchronizedclass BSTMapTest {
BSTMap m;
public void BSTMapTest();
public void startUp();
public void testGetLeft();
public void testGetRight();
public void testGetParent();
public void testIsLeaf();
public void testSetLeft();
public void testSetRight();
public void testSetParent();
}
BSTMapTest.javaBSTMapTest.javaimportstatic org.junit.Assert
.*;
import org.junit.Before;
import org.junit.Test;
publicclassBSTMapTest{
BSTMap m;
/**
* startUp creates a new instance of BSTMap.
*/
@Before
publicvoid startUp(){
m=newBSTMap(1,"one");
}
/**
* testGetLeft tests getLeft().
*
* It tests when it doesnt exist, when it does exist, when it ha
s been changed, and when it has been removed.
*/
@Test
publicvoid testGetLeft(){
assertEquals(null, m.getLeft());
m.setRight(newBSTMap(3,"three"));
assertEquals(null, m.getLeft());
BSTMap child=newBSTMap(2,"two");
BSTMap a=newBSTMap(1,"a");
m.setLeft(child);
assertEquals(child, m.getLeft());
m.setLeft(a);
assertEquals(a, m.getLeft());
m.setLeft(null);
assertEquals(null, m.getLeft());
}
/**
* testGetRight tests getRight().
*
* It tests when it doesnt exist, when it does exist, and when i
t has been removed.
*/
@Test
publicvoid testGetRight(){
assertEquals(null, m.getRight());
m.setLeft(newBSTMap(2,"two"));
assertEquals(null, m.getRight());
BSTMap child =newBSTMap(3,"three");
BSTMap a=newBSTMap(1,"a");
m.setRight(child);
assertEquals(child, m.getRight());
m.setRight(a);
assertEquals(a, m.getRight());
m.setRight(null);
assertEquals(null, m.getRight());
}
/**
* testGetParent tests getParent()
*
* It tests when there is a parent, when there is not a parent.
*/
@Test
publicvoid testGetParent(){
assertEquals(null, m.getParent());
m.setLeft(newBSTMap(2,"two"));
assertEquals(null, m.getParent());
BSTMap child =newBSTMap(3,"three");
m.setRight(child);
assertEquals(m, child.getParent());
}
/**
* testIsLeaf tests to see if a node is a leaf.
*
* It tests when it has no children, when it has a left child, a
right child, both, and when they have been removed.
*/
@Test
publicvoid testIsLeaf(){
assertTrue(m.isLeaf());
m.setLeft(newBSTMap(2,"two"));
assertFalse(m.isLeaf());
m.setRight(newBSTMap(3,"three"));
assertFalse(m.isLeaf());
m.setLeft(null);
assertFalse(m.isLeaf());
m.setRight(null);
assertTrue(m.isLeaf());
}
/**
* testSetLeft tests setLeft()
*
*/
@Test
publicvoid testSetLeft(){
assertEquals(null, m.getLeft());
BSTMap child=newBSTMap(2,"two");
m.setLeft(child);
m.setRight(newBSTMap(3,"three"));
assertEquals(child,m.getLeft());
m.setLeft(null);
assertEquals(null,m.getLeft());
}
/**
* testSetRight tests setRight
*/
@Test
publicvoid testSetRight(){
BSTMap child=newBSTMap(2,"two");
BSTMap a=newBSTMap(1,"a");
assertEquals(null, a.getRight());
a.setRight(child);
assertEquals(child, a.getRight());
a.setRight(null);
assertEquals(null, a.getRight());
}
/**
* testSetParent tests setParent
*/
@Test
publicvoid testSetParent(){
BSTMap child=newBSTMap(2,"two");
BSTMap a=newBSTMap(1,"a");
assertEquals(null, a.getParent());
a.setParent(child);
assertEquals(child, a.getParent());
a.setParent(null);
assertEquals(null, a.getParent());
}
}
HTree.classpublicsynchronizedclass HTree {
private String s;
private int f;
HTree l;
HTree r;
public void HTree(int, String);
public void setL(HTree);
public void setR(HTree);
public HTree getL();
public HTree getR();
public String getS();
public int getF();
public boolean isLeaf();
public int getBelow();
}
HTree.javaHTree.java
publicclassHTree<E extendsComparable<E>>{
privateString s;
privateint f;
HTree l;
HTree r;
/**
* HTree creates a HTree object containing a int frequency an
d a String str.
* @param frequency the integer frequency of the str
* @param str the str value of this HTree
*/
publicHTree(int frequency,String str){
s=str;
f=frequency;
l=null;
r=null;
}
/**
* setL sets the left HTree value
* @param left the HTree that is the left child of this node
*/
publicvoid setL(HTree left){
l=left;
}
/**
* setR sets the right HTree child value
* @param right the HTree that is the right child of this node
*/
publicvoid setR(HTree right){
r=right;
}
/**
* getL returns the left child of this node.
* @return HTree the left child.
*/
publicHTree getL(){
return l;
}
/**
* getR returns the right child of this node.
* @return HTree the right child.
*/
publicHTree getR(){
return r;
}
/**
* getS returns the string value associated with this node
* @return String the value of this node
*/
publicString getS(){
return s;
}
/**
* getF returns the frequency value associated with this node.
* @return the int frequency value associated with this node.
*/
publicint getF(){
return f;
}
/**
* isLeaf returns boolean if this node is a leaf.
* @return boolean wether this node is a leaf.
*/
publicboolean isLeaf(){
if(l==null&&r==null){
returntrue;
}
returnfalse;
}
/**
* getBelow recursively finds how many children this node h
as.
*
* **this does not handle trees with only one child (as this do
es not occur in a huffmanTree)
* @return the int number height
*/
publicint getBelow(){
if(isLeaf()){
return0;
}else{
int a=1+l.getBelow();
int b=1+r.getBelow();
if(a>b){
System.out.println("returning a: "+ a);
return a;
}
System.out.println("returning b"+ b);
return b;
}
}
}
HeapTest.classpublicsynchronizedclass HeapTest {
Heap h;
Heap min;
public void HeapTest();
public void start();
public void testFindMax();
public void testRemoveMax();
public void testSize();
public void testMin();
}
HeapTest.javaHeapTest.javaimportstatic org.junit.Assert.*;
import java.util.Comparator;
import org.junit.Before;
import org.junit.Test;
publicclassHeapTest{
Heap h;
Heap min;
/**
* start creates a test case of heap both min and max compara
tor.
*/
@Before
publicvoid start(){
Comparator<Integer> c =newHeap.MaxHeapComparator<Intege
r>();
Comparator<Integer> m =newHeap.MinHeapComparator<Intege
r>();
min=newHeap(10,m);
min.insert(1);
min.insert(2);
min.insert(3);
min.insert(4);
h=newHeap(10,c);
System.out.println("this is 1");
h.insert(1);
System.out.println(h.h[0]);
System.out.println("this is 2");
h.insert(2);
System.out.println(h.h[0]+","+h.h[1]);
System.out.println("this is 3");
h.insert(3);
System.out.println(h.h[0]+","+h.h[1]+","+h.h[2]);
System.out.println("this is 4");
h.insert(4);
System.out.println(h.h[0]+","+h.h[1]+","+h.h[2]+","+h.h[3]);
}
/**
* testFindMax tests the findMax function
*/
@Test
publicvoid testFindMax(){
assertEquals(4, h.findMax());
assertEquals(4, h.removeMax());
assertEquals(3, h.findMax());
assertEquals(1, min.findMax());
assertEquals(1, min.removeMax());
assertEquals(2, min.findMax());
}
/**
* testRemoveMax tests the remove max function
*/
@Test
publicvoid testRemoveMax(){
assertEquals(4, h.findMax());
assertEquals(4,h.removeMax());
assertEquals(3, h.findMax());
assertEquals(3,h.removeMax());
assertEquals(2,h.removeMax());
assertEquals(1,h.removeMax());
assertEquals(0,h.size());
assertEquals(1, min.findMax());
}
/**
* testSize tests the size function of heap.
*/
@Test
publicvoid testSize(){
assertEquals(4, h.size());
int o=(Integer) h.removeMax();
assertEquals(3, h.size());
h.insert(o);
assertEquals(4, h.size());
h.removeMax();
h.removeMax();
h.removeMax();
h.removeMax();
assertEquals(0, h.size());
assertEquals(4, min.size());
}
/**
* testMin tests the minSort comparator.
*/
@Test
publicvoid testMin(){
assertEquals(4, min.size());
assertEquals(1,min.removeMax());
assertEquals(2,min.removeMax());
assertEquals(3,min.removeMax());
assertEquals(4,min.removeMax());
}
}
HuffmanTree$CountPair.classsynchronizedclass
HuffmanTree$CountPair {
int _count;
String _text;
private void HuffmanTree$CountPair(HuffmanTree, String,
int);
}
HuffmanTree$CountPairTreeComparator.classsynchronizedclass
HuffmanTree$CountPairTreeComparator implements
java.util.Comparator {
private void
HuffmanTree$CountPairTreeComparator(HuffmanTree);
public int compare(BinaryTree, BinaryTree);
}
HuffmanTree.classpublicsynchronizedclass HuffmanTree {
java.io.File current;
BSTMap _lookupTable;
BinaryTree _huffmanTree;
public void HuffmanTree();
publicstatic HuffmanTree newTreeFromFile(java.io.File)
throws java.io.FileNotFoundException;
publicstatic HuffmanTree
newTreeFromCompressedFile(java.io.File) throws
java.io.FileNotFoundException;
private void buildFromFile(java.io.File) throws
java.io.FileNotFoundException;
private void buildTreeFromMap(PriorityQueue);
private void buildFromCompressedFile(java.io.File) throws
java.io.FileNotFoundException;
public void saveCompressedFile(java.io.File);
public void saveExpandedFile(java.io.File);
public String encode(String);
public String decode(String);
}
HuffmanTree.javaHuffmanTree.javaimport java.io.File;
import java.io.FileNotFoundException;
import java.util.Comparator;
import java.util.Scanner;
import java.util.Set;
/**
* This class implements the basic functionality of Huffman co
mpression and expansion.
*
* @author C. Andrews
*
*/
publicclassHuffmanTree{
File current;
BSTMap<String,String> _lookupTable =newBSTMap<String,Str
ing>(null,null);
BinaryTree<CountPair> _huffmanTree;
/**
* This is a factory method for reading in a fresh text file to i
nitialize the Huffman tree.
*
* @param file the document to use for the code frequencies
* @return a HuffmanTree containing the Huffman codes bas
ed on the frequencies observed in the document
* @throws FileNotFoundException
*/
publicstaticHuffmanTree newTreeFromFile(File file)throwsFile
NotFoundException{
HuffmanTree tree =newHuffmanTree();
tree.buildFromFile(file);
return tree;
}
/**
* This is a factory method that builds a new HuffmanTree fr
om a compressed file.
*
* @param file a file that has been compressed with a Huffma
n tool
* @return a new HuffmanTree containing the codes for deco
ding the file
* @throws FileNotFoundException
*/
publicstaticHuffmanTree newTreeFromCompressedFile(File file
)throwsFileNotFoundException{
// TODO implement this
}
/**
* This method builds the Huffman tree from the input file.
*
* @param file the file to use to construct the Huffman tree
* @throws FileNotFoundException
*/
privatevoid buildFromFile(File file)throwsFileNotFoundExcepti
on{
current=file;
// read file and build the map of the character frequencies
Map<String,Integer> freqMap =newBSTMap<String,Integer>();
Scanner scanner =newScanner(file);
scanner.useDelimiter("");
String character;
while(scanner.hasNext()){
character = scanner.next();
Integer count = freqMap.get(character);
if(count ==null){
count =Integer.valueOf(0);
}
freqMap.put(character, count+1);
}
// for each key, make a tree and load it into the priority queue
PriorityQueue<BinaryTree<CountPair>> treeQueue =newPriorit
yQueue<BinaryTree<CountPair>>(freqMap.keySet().size(),new
CountPairTreeComparator());
BinaryTree<CountPair> tmpTree;
for(String key: freqMap.keySet()){
int frequency = freqMap.get(key);
tmpTree =newBinaryTree<CountPair>(null,newCountPa
ir(key, frequency),null);
treeQueue.add(tmpTree);
}
// while the size of the priority queue is greater than 1, combine
the top items into a tree and put them back in the priority queue
BinaryTree<CountPair> tree1, tree2;
int newFrequency;
String newText;
while(treeQueue.size()>1){
tree1 = treeQueue.remove();
tree2 = treeQueue.remove();
// If the height of the second tree is less than the height of the fi
rst,
// or the heights are the same and tree2 precedes tree1 alphabeti
cally, swap them so
// the smaller/earlier tree is put on the left
if(tree1.getValue()._text.length()> tree2.getValue()._text.length
()
||( tree1.getValue()._text.length()== tree2.getValue()._text.lengt
h()
&& tree1.getValue()._text.compareTo(tree2.getValue()._text)>0
)){
tmpTree = tree1;
tree1 = tree2;
tree2 = tmpTree;
}
// create a new tree combining the two smaller trees, computing
a new frequency that is the sum of the
// children frequencies and a new text that is the appended comb
ination of the children's text
newFrequency = tree1.getValue()._count + tree2.getVal
ue()._count;
newText = tree1.getValue()._text + tree2.getValue()._te
xt;
tmpTree =newBinaryTree<CountPair>(tree1,newCountP
air(newText, newFrequency), tree2);
treeQueue.add(tmpTree);
}
// pull the completed tree from the priority queue
BinaryTree<CountPair> tree = treeQueue.remove();
// create map of symbols to code lengths using the tree
Map<String,Integer> codeLengthMap =newMap<String,Integer>
();
// TODO implement this part
PriorityQueue pq=newPriorityQueue(setC.size(),new treeCompa
rator());
buildTreeFromMap(pq);
}
privatevoid buildTreeFromMap(PriorityQueue q){
// TODO Auto-generated method stub
}
/**
* Builds the tree using information found in a compressed fil
e.
*
* The table is the first thing we find in the file. The first pie
ce of data is the length
* of the table (L). This is followed by L pairs of character an
d code length pairs.
*
* @param file the file to read the Huffman code from.
*/
privatevoid buildFromCompressedFile(File file)throwsFileNotF
oundException{
// TODO implement this
}
/**
* Read the original file and compress it using the Huffman cod
es, writing the result
* into the output file.
*
* @param outputFile the output file
*/
publicvoid saveCompressedFile(File outputFile){
// TODO implement this
}
/**
* Read the compressed file that initialized this object and wr
ite the decoded version out
* into the output file.
*
* @param outputFile the destination file for the uncompress
ed file.
*/
publicvoid saveExpandedFile(File outputFile){
// TODO implement this
}
/**
* This method reads in a String of text and returns a String o
f 0s and 1s corresponding to the Huffman code stored in this tre
e.
* @param text the text to be encoded
* @return a String representation of the Huffman code
*/
publicString encode(String text){
StringBuilder builder =newStringBuilder();
String tmp;
for(int i =0; i < text.length(); i++){
tmp = _lookupTable.get(String.valueOf(text.charAt(i)));
builder.append(tmp);
}
return builder.toString();
}
/**
* This method reads in a String representation of a Huffman
code corresponding to this Huffman tree and decodes it.
* @param text a String representation of the a Huffman code
d message
* @return the original text
*/
publicString decode(String text){
StringBuilder builder =newStringBuilder();
BinaryTree<CountPair> current = _huffmanTree;
for(int i =0; i < text.length(); i++){
char c = text.charAt(i);
if(c =='0'){
current = current.getLeftChild();
}elseif(c =='1'){
current = current.getRightChild();
}else{
thrownewRuntimeException("Encountered unexpected character
in coded String");
}
if(current.isLeaf()){
builder.append(current.getValue()._text);
current = _huffmanTree;
}
}
return builder.toString();
}
privateclassCountPair{
int _count;
String _text;
privateCountPair(String text,int count){
_text = text;
_count = count;
}
}
privateclassCountPairTreeComparatorimplementsComparator<B
inaryTree<CountPair>>{
@Override
publicint compare(BinaryTree<CountPair> t1,BinaryTree<Coun
tPair> t2){
CountPair p1 = t1.getValue();
CountPair p2 = t2.getValue();
if(p1._count != p2._count){
return p2._count - p1._count;
}elseif(p1._text.length()!= p2._text.length()){
return-p1._text.length()- p2._text.length();
}else{
return p1._text.compareTo(p2._text);
}
}
}
}
nObjectTest.classpublicsynchronizedclass nObjectTest {
nObject o;
public void nObjectTest();
public void setUp();
public void testChangeKey();
public void testChangeValue();
public void testGetKey();
public void testGetValue();
}
nObjectTest.javanObjectTest.javaimportstatic org.junit.Assert.*
;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
publicclass nObjectTest {
nObject o;
/**
* setUp sets up the test.
*/
@Before
publicvoid setUp(){
o=new nObject("one",1);
}
/**
* tests the change Key function
*/
@Test
publicvoid testChangeKey(){
assertEquals("one", o.getKey());
o.changeKey("two");
assertEquals("two", o.getKey());
}
/**
* tests the change Value function
*/
@Test
publicvoid testChangeValue(){
assertEquals(1, o.getValue());
o.changeValue(2);
assertEquals(2, o.getValue());
}
/**
* testGetKey tests the getKey method
*/
@Test
publicvoid testGetKey(){
assertEquals("one", o.getKey());
o.changeKey("two");
assertEquals("two", o.getKey());
}
/**
* testGetValue tests get Value
*/
@Test
publicvoid testGetValue(){
assertEquals(1, o.getValue());
o.changeValue(2);
assertEquals(2, o.getValue());
}
}
MapTest.classpublicsynchronizedclass MapTest {
Map m;
public void MapTest();
public void start();
public void testContainsKey();
public void testGet();
public void testKeySet();
public void testPut();
public void testRemove();
}
MapTest.javaMapTest.javaimportstatic org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
publicclassMapTest{
Map m;
/**
* start() creates an initial map to test.
*/
@Before
publicvoid start(){
m=newMap();
}
/**
* testContainsKey tests the containsKey function.
* It tests when there are more than one object, one object,
* when the object is contained, and when the object is not co
ntained.
*/
@Test
publicvoid testContainsKey(){
assertFalse(m.containsKey(5));
m.put(5,"five");
m.put(4,"four");
assertTrue( m.containsKey(5));
m.remove(5);
assertFalse(m.containsKey(5));
m.remove(4);
assertFalse(m.containsKey(4));
}
/**
* testGet tests the get function of map.
*
* It tests when there are no objects, when there is an object,
and when there are more than one objects.
*/
@Test
publicvoid testGet(){
assertEquals(null, m.get(5));
m.put(5,"five");
assertEquals("five",m.get(5));
m.put(4,"four");
assertEquals("five",m.get(5));
}
/**
* testKeySet tests keySet.
*/
@Test
publicvoid testKeySet(){
assertEquals(true, m.keySet().isEmpty());
m.put(5,"five");
assertEquals(false, m.keySet().isEmpty());
assertEquals(true, m.keySet().contains(5));
}
/**
* testPut tests the put method of map.
*/
@Test
publicvoid testPut(){
assertEquals(null, m.get(5));
m.put(5,"five");
assertEquals("five",m.get(5));
m.put(5,"changed");
m.put(6,"six");
assertEquals("changed",m.get(5));
assertEquals("six",m.get(6));
}
/**
* testRemove tests map's remove function
*
* It tests if it can remove something that isnt in map, and re
moval of objects not in order.
*/
@Test
publicvoid testRemove(){
assertEquals(null, m.remove("a"));
m.put(5,"five");
m.put(4,"four");
m.put(3,"three");
assertEquals("three", m.remove(3));
assertEquals("five", m.remove(5));
assertEquals("four", m.remove(4));
}
}
.project
assignment 8
org.eclipse.jdt.core.javabuilder
org.eclipse.jdt.core.javanature
META-INF/MANIFEST.MF
Manifest-Version: 1.0
.classpath
PriorityQueue.classpublicsynchronizedclass PriorityQueue {
Heap q;
public void PriorityQueue(int, java.util.Comparator);
public Object peek();
public Object remove();
void add(Object);
boolean isEmpty();
public int size();
}
PriorityQueue.javaPriorityQueue.javaimport java.util.Comparat
or;
publicclassPriorityQueue<E>{
Heap q;
/**
*PriorityQueue initializes the queue.
*
* @param initialCapacity an int that is the heaps initial size.
* @param comparator the priority of various imputs.
*/
publicPriorityQueue(int initialCapacity,Comparator<?super E>
comparator){
q=newHeap(initialCapacity,comparator);
}
/**
* Peek, returns the next item in the queue without removing
it.
*
* If it is empty then null is returned.
* @return the next item in the queue.
*/
public E peek(){
if(q.size()==0){
returnnull;
}
return(E) q.findMax();
}
/**
* This removes the first item from the queue.
*
* It returns null if the queue is empty.
* @return the first item in the queue.
*/
public E remove(){
if(q.size()==0){
returnnull;
}
return(E) q.removeMax();
}
/**
* This adds item to the queue
* @param item that is added to the queue.
*/
void add(E item){
q.insert(item);
}
/**
* isEmpty returns if the queue is empty or not.
*
* @return boolean if the queue is empty or not.
*/
boolean isEmpty(){
if(q.size()!=0){
returnfalse;
}
returntrue;
}
/**
* size returns the size of the queue.
*
* @return int the size of the queue.
*/
publicint size(){
return q.size();
}
}
ArithmeticExpression.classpublicsynchronizedclass
ArithmeticExpression {
BinaryTree t;
java.util.ArrayList list;
String equation;
void ArithmeticExpression(String) throws
java.text.ParseException;
public String toString(BinaryTree);
public String toPostfixString(BinaryTree);
void setVariable(String, int) throws
java.rmi.NotBoundException;
public int evaluate(BinaryTree);
}
ArithmeticExpression.javaArithmeticExpression.javaimport java
.rmi.NotBoundException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Stack;
/**
* ArithmeticExpression takes equations in the form of strings c
reates a binary
* tree, and can return either the regular or postfix equation. It a
lso allows
* them to be calculated.
*
*
* Extra Credit:
* ** it can handle spaces or no spaces in the string inputted. **
it can return
* regular or postfix notation
*
* @author tai-lanhirabayashi
*
*/
publicclassArithmeticExpression{
BinaryTree t;
ArrayList list;
String equation;
/**
* ArithmeticExpression is the construction which takes in a
space
* delimitated equation containing "*,/,+,-
" symbols and converts it into a
* binary tree.
*
* If the expression is not valid it will throw a ParseExceptio
n. This is
* the constructor. It will take a String containing the express
ion.
*
* ** The equation can take in stings delimitated by spaces, o
r withot any
* spaces. If it contains a mix, then the non spaced part(s) wil
l be
* considered to be a variable.
*
* @param expression
* @throws ParseException
* if the string is not a valid equation
*/
@SuppressWarnings({"unchecked","rawtypes"})
ArithmeticExpression(String expression)throwsParseException{
//hold the string globally
equation = expression;
//create a new arrayList to be used globally that holds the variab
les
list =newArrayList();
//split the string
String[] s = expression.split(" ");
// create a stack of tree's and operators
Stack tree =newStack();
Stack operator =newStack();
//create the string Next
String next ="";
// if the string expression doesnt contain spaces
if(!expression.contains(" ")){
int i =0;
//if it starts with an operator throw an error this cannot be.
if(expression.charAt(0)=='+'|| expression.charAt(0)=='*'
|| expression.charAt(0)=='-'
|| expression.charAt(0)=='/'){
System.out.println("this equation starts with a operator.");
thrownewParseException(expression,0);
}
// if the expression ends with an operator throw an error this can
not be.
if(expression.charAt(expression.length()-1)=='+'
|| expression.charAt(expression.length()-1)=='*'
|| expression.charAt(expression.length()-1)=='-'
|| expression.charAt(expression.length()-1)=='/'){
System.out.println("this equation ends with a operator.");
thrownewParseException(expression, expression.length());
}
//go through each characer in the expression and see if its a num
ber/variable, or operator.
while(i < expression.length()){
if(expression.charAt(i)=='+'|| expression.charAt(i)=='*'
|| expression.charAt(i)=='-'
|| expression.charAt(i)=='/'){
// if the character is a operator add a space to the begining and f
ront and add it to the "next" string
String str =String.valueOf(expression.charAt(i));
next = next +" "+ str +" ";
}else{
// if its an operator add it to the end of the "next" string.
next = next + expression.charAt(i);
}
// increase i to move to the next character.
i++;
}
// split the new string with added spaces.
s = next.split(" ");
}
// if the string still doesnt exist throw the error.
if(s.length ==0){
System.out
.println("there has been an error. You have not entered a string
with any characters");
thrownewParseException(expression,0);
}
// make sure there arent two operators in a row.
for(int i =0; i < s.length; i++){
if(i >=1
&&(s[i].equals("+")|| s[i].equals("-")
|| s[i].equals("*")|| s[i].equals("/"))){
if(s[i -1].equals("+")|| s[i -1].equals("-")
|| s[i -1].equals("*")|| s[i -1].equals("/")){
System.out
.println("there were two operators in a row. The equation is not
valid.");
thrownewParseException(expression, i);
}
}
// check to make sure there arent two operands in a row in the St
ring[]
if(i >=1
&&(s[i].equals("+")==false&& s[i].equals("-")==false
&& s[i].equals("*")==false&& s[i].equals("/")==false)){
if(s[i -1].equals("+")==false
&& s[i -1].equals("-")==false
&& s[i -1].equals("*")==false
&& s[i -1].equals("/")==false){
System.out
.println("there were two operands in a row. The equation is not
valid.");
thrownewParseException(expression, i);
}
}
// if its a number create a new tree node, and add it to the tree st
ack
if(s[i].equals("+")==false&& s[i].equals("-")==false
&& s[i].equals("*")==false&& s[i].equals("/")==false){
BinaryTree o =newBinaryTree(null, s[i],null);
tree.add(o);
}elseif(operator.empty()|| s[i].equals("*")|| s[i].equals("/")){
//if its a * or / symbol hold it to ensure order of operation
operator.push(s[i]);
}else{
//group the tree's together.
while(operator.empty()==false){
String operatorHeld =(String) operator.pop();
BinaryTree one =(BinaryTree) tree.pop();
BinaryTree two =(BinaryTree) tree.pop();
BinaryTree n =newBinaryTree(one, operatorHeld, two);
tree.push(n);
}
operator.push(s[i]);
}
}
// at the end ensure that the operator is empty.
while(operator.empty()==false){
String operatorHeld =(String) operator.pop();
BinaryTree one =(BinaryTree) tree.pop();
BinaryTree two =(BinaryTree) tree.pop();
BinaryTree n =newBinaryTree(one, operatorHeld, two);
tree.push(n);
}
//if there is more than 1 tree at the end something went wrong
// this should not occur as it should have been caught earlier
// this is just to ensure completeness.
if(tree.size()>=2){
System.out
.println("this expression is invalid. There were more operands t
han operators.");
System.out
.println("this should not occur it should have been caught earlie
r");
while(tree.empty()==false){
return;
}
}
//if there are still operators there is something wrong
// this should not occur as it should have been caught earlier
// this is just to ensure completeness.
if(operator.empty()==false){
System.out
.println("this should not occur it should have been caught earlie
r.");
System.out
.println("there were too many operators in the string the progra
m cannot continue.");
{
return;
}
}
// set the tree globally
t =(BinaryTree) tree.pop();
}
/**
* toString returns the String equation of that the passed in bi
nary tree
* represents.
*
* @param tree
* that represents an equation
* @return the String that is represented by the passed in Bin
aryTree.
*/
@SuppressWarnings("rawtypes")
publicString toString(BinaryTree tree){
// if its a leaf return its value
if(tree.isLeaf()==true){
return(String) tree.getValue();
}else{
//else combine each parent child combination
//call recursively, and contain each call in parenthesis.
String s =("("+ toString(tree.getLeftChild())+ tree.getValue()
+ toString(tree.getRightChild())+")");
return s;
}
}
/**
* toPostfixString returns the string containing the parsed exp
ression in
* postFix notation with spaces between numbers and operato
rs to ensure clarity.
*
* @param tree that represents an equation
* @return the String that is represented by the passed in Bin
aryTree in
* postfix form.
*/
@SuppressWarnings("unchecked")
publicString toPostfixString(BinaryTree tree){
//if its a leaf return its value
if(tree.isLeaf()==true){
return(String) tree.getValue();
}else{
//otherwise call recursively down the tree
// and add the operator to the end of the two operands.
// also add spaces to allow numbers to be seen individually.
String s = toPostfixString(tree.getRightChild())+" "
+ toPostfixString(tree.getLeftChild())+" "
+ tree.getValue();
System.out.println("this is what s is "+ s);
return s;
}
}
/**
* This allows the user to set a value for a variable in the exp
ression. If
* the variable does not exist in the function, throw a NotBou
ndException.
*
* @param name of the variable
* @param value that the variable has
* @throws NotBoundException if the variable is not used in
the equation
*/
void setVariable(String name,int value)throwsNotBoundExcepti
on{
//Note var, is not a Var it is a seperate class that is an object.
//if the equation string doesnt contain the variable throw an erro
r
if(!equation.contains(name)){
thrownewNotBoundException();
}
// else continue and check if the var object is already in the list
for(int i =0; i < list.size(); i++){
var v =(var) list.get(i);
if(v.getName().equals(name)){
//if so change the value of the var object
v.setValue(value);
return;
}
}
// otherwise add the var object to the list.
list.add(new var(name, value));
}
/**
* Evaluate returns the integer result of the expression.
*
* Variables that are not declared are calculated at 0.
*
* @return the value of the equation
*/
@SuppressWarnings("unused")
publicint evaluate(BinaryTree tree){
//if it is a leaf
if(tree.isLeaf()==true){
String s =(String) tree.getValue();
//if all characters are numbers simply skip down to return the in
teger value.
for(int i =0; i < s.length(); i++){
if(s.charAt(i)=='0'|| s.charAt(i)==('1')
|| s.charAt(i)=='2'|| s.charAt(i)=='3'
|| s.charAt(i)=='4'|| s.charAt(i)=='5'
|| s.charAt(i)=='6'|| s.charAt(i)=='7'
|| s.charAt(i)=='8'|| s.charAt(i)=='9'){
}else{
//if there are non numeric characters check if the list has their v
alues
for(int j =0; j < list.size(); j++){
var h =(var) list.get(j);
if(h.getName().equals(s)){
return h.getValue();
}
}
//otherwise tell the user that this variable cannot be found and t
hat its value is calulated at 0
System.out.println("this variable "+ s
+" cannot be found! Its value will be 0.");
return0;
}
returnInteger.parseInt((String) tree.getValue());
}
}
//find the left and right values of the tree
int left = evaluate(tree.getLeftChild());
int right = evaluate(tree.getRightChild());
//calculate appropriately.
if(tree.getValue().equals("*")){
return left * right;
}elseif(tree.getValue().equals("/")){
return left / right;
}elseif(tree.getValue().equals("+")){
return left + right;
}
return left - right;
}
}
Map.classpublicsynchronizedclass Map {
BSTMap root;
BSTMap found;
java.util.TreeSet set;
public void Map();
public void put(Comparable, Object);
public Object get(Comparable);
public boolean containsKey(Comparable);
private BSTMap getBSTMap(Comparable);
public Object remove(Comparable);
private BSTMap sucessor(BSTMap);
public java.util.Set keySet();
}
Map.javaMap.javaimport java.util.Set;
import java.util.TreeSet;
publicclassMap<K extendsComparable<K>,V>{
BSTMap root;
BSTMap found;
TreeSet<K> set;
/**
* Map initializes the map.
*/
publicMap(){
set=newTreeSet<K>();
root=null;
found=null;
}
/**
* put loads the Key and value into a BSTMap object, and the
key into the set.
*
* If the key already exists the value is changed to the new va
lue.
* @param key the K key value
* @param value the V value value
*/
publicvoid put(K key, V value){
//if the root is null this is the root
if(root==null){
root=newBSTMap(key,value);
set.add(key);
//if the key exists then change the value
}elseif(get(key)!=null){
getBSTMap(key).obj.value=value;
}else{
//otherwise create a new BSTMap
BSTMap i =newBSTMap(key,value);
//add it to the set
set.add(key);
//and find its place in the BSTmap tree.No key can be identical.
boolean done=false;
BSTMap c= root;
while(done==false){
//if it is bigger go right
if(key.compareTo((K) c.obj.getKey())>=0){
if(c.getRight()==null){
c.setRight(i);
done=true;
}else{
c=c.getRight();
}
//if it is smaller go left.
}elseif(key.compareTo((K) c.obj.getKey())<0){
if(c.getLeft()==null){
c.setLeft(i);
done=true;
}else{
c=c.getLeft();
}
}
}
}
}
/**
* This finds the value associated with they key. If this key c
annot be found null is returned.
* @param key the K key value
* @return V the associated V value.
*/
public V get(K key){
BSTMap current= root;
if(root==null){
returnnull;
}
while(current!=null&& current.obj.getKey().equals(key)==false
){
if(key.compareTo((K) current.obj.getKey())<0){
current=current.getLeft();
}else{
current=current.getRight();
}
}
if(current==null){
returnnull;
}
if(current.obj.getKey().equals(key)){
return(V) current.obj.getValue();
}
returnnull;
}
/**
*containsKey returns boolean if the key exists in the map.
* @param key the K key value to look for
* @return boolean if it exists
*/
publicboolean containsKey(K key){
BSTMap current= root;
if(root==null){
returnfalse;
}
while(current!=null&& current.obj.getKey().equals(key)==false
){
if(key.compareTo((K) current.obj.getKey())<0){
current=current.getLeft();
}else{
current=current.getRight();
}
}
if(current==null){
returnfalse;
}
return current.obj.getKey().equals(key);
}
/**
* getBSTMap returns the BSTMap associated with a key val
ue
* @param key the K key value
* @return BSTMap contained the K key.
*/
privateBSTMap getBSTMap(K key){
BSTMap current= root;
if(root==null){
returnnull;
}
while(current!=null&& current.obj.getKey().equals(key)==false
){
if(key.compareTo((K) current.obj.getKey())<0){
current=current.getLeft();
}else{
current=current.getRight();
}
}
if(current.obj.getKey().equals(key)){
return current;
}
returnnull;
}
/**
* remove removes the BSTMap associated with they key, an
d returns its associated value.
*
* If the key cannot be found null is returned
* @param key the K key value to be found
* @return V the value of associated with the BSTMap contai
ning the K key value.
*/
public V remove(K key){
if(root==null){
returnnull;
}elseif(root.obj.getKey().equals(key)){
System.out.println("the node to remove is the root.");
V val=(V) root.obj.getValue();
if(root.isLeaf()){
root=null;
}elseif(root.getLeft()==null){
root=root.getRight();
}elseif(root.getRight()==null){
root=root.getLeft();
}else{
root=sucessor(root);
}
return val;
}
BSTMap n= getBSTMap(key);
if(n==null){
returnnull;
}else{
set.remove(key);
V a=(V) n.obj.getValue();
BSTMap temp=null;
BSTMap child=null;
if(n.isLeaf()){
temp=n;
n=null;
}elseif(n.getLeft()!=null&& n.getLeft().getRight()==null){
temp=n;
n.getLeft().setRight(n.right);
n.setLeft(null);
}elseif(n.getRight()!=null&& n.getRight().getLeft()==null){
temp=n;
n.getRight().setLeft(n.getLeft());
n.setRight(null);
}else{
temp=sucessor(n);
n.setRight(null);
}
System.out.println("this is the temp:"+
temp.obj.key);
if(temp.getLeft()!=null){
child=temp.getLeft();
}else{
child=temp.getRight();
}if(child!=null){
child.parent=temp.parent;
}if(temp.parent.getLeft()==temp){
temp.parent.setLeft(child);
}else{
temp.parent.setRight(child);
}
return a;
}
}
privateBSTMap sucessor(BSTMap n){
boolean running=true;
BSTMap current=n.getRight();
while(running){
if(current.getLeft()!=null){
current=current.getLeft();
}else{
running=false;
}
}
return current;
}
/**
* keySet returns a Set of the K key values in the map.
* @return
*/
publicSet<K> keySet(){
return set;
}
}
BinaryTree.classpublicsynchronizedclass BinaryTree {
Object v;
BinaryTree treeLeft;
BinaryTree treeRight;
void BinaryTree(BinaryTree, Object, BinaryTree);
BinaryTree getLeftChild();
BinaryTree getRightChild();
void setLeftChild(BinaryTree);
void setRightChild(BinaryTree);
void setValue(Object);
Object getValue();
boolean isLeaf();
}
BinaryTree.javaBinaryTree.java
/**
* BinaryTree is a form of linked nodes that form a tree.
*
* @author tai-lan hirabayashi
*
* @param <E> the object value that is within each node.
*/
publicclassBinaryTree<E>{
E v;
BinaryTree<E> treeLeft;
BinaryTree<E> treeRight;
/**
* BinaryTree creates a new node binaryTree which holds an
object value.
* It takes in the value, left and right child and holds them wi
thin the node.
* @param left the left child of the node.
* @param value the object the node holds
* @param right the right child of the node
*/
BinaryTree(BinaryTree<E> left, E value,BinaryTree<E> right){
v=value;
treeLeft=left;
treeRight=right;
}
/**
* getLeftChild returns the left child node.
* @return the left child, a binary tree node.
*/
BinaryTree<E> getLeftChild(){
return treeLeft;
}
/**
* getRightChild returns the right child node.
* @return the right child,a binaryTree node.
*/
BinaryTree<E> getRightChild(){
return treeRight;
}
/**
* setLeftChild, sets the left child of the current node.
* @param l is the left child, a binaryTree node.
*/
void setLeftChild(BinaryTree<E> l){
treeLeft=l;
}
/**
* setRightChild, sets the right child of the current node.
* @param r the right child, a binaryTree node.
*/
void setRightChild(BinaryTree<E> r){
treeRight=r;
}
/**
* setValue sets the value of a node.
* @param object value of the node.
*/
void setValue(E object){
v=object;
}
/**
* getValue returns the value held in the node.
* @return the object value of the node.
*/
E getValue(){
return v;
}
/**
* isLeaf checks if the node is a leaf node by checking if it ha
s children.
* @return boolean if the node is a leaf node.
*/
boolean isLeaf(){
if(getLeftChild()==null&& getRightChild()==null){
returntrue;
}
returnfalse;
}
}
HuffmanTreeTest.classpublicsynchronizedclass
HuffmanTreeTest {
HuffmanTree h;
String t;
public void HuffmanTreeTest();
public void start() throws java.io.FileNotFoundException;
public void testEncode();
public void testDecode();
}
HuffmanTreeTest.javaHuffmanTreeTest.java
importstatic org.junit.Assert.*;
import java.io.File;
import java.io.FileNotFoundException;
import org.junit.Before;
import org.junit.Test;
publicclassHuffmanTreeTest{
HuffmanTree h;
String t;
/**
* start creates a test case
* @throws FileNotFoundException
*/
@Before
publicvoid start()throwsFileNotFoundException{
h =HuffmanTree.newTreeFromFile(newFile("/Users/tai-
lanhirabayashi/Desktop/test.txt"));
}
/**
* testEncode tries to encode a string.
*/
@Test
publicvoid testEncode(){
t = h.encode("This program must work!");
}
/**
* testDecode tries to decode the string.
*/
@Test
publicvoid testDecode(){
assertEquals("This program must work!", h.decode(t));
}
}
HTreeTest.classpublicsynchronizedclass HTreeTest {
HTree t;
public void HTreeTest();
public void start();
public void testGetBelow();
public void testGetF();
public void testGetS();
public void testGetL();
public void testGetR();
public void testIsLeaf();
public void testSetL();
public void testSetR();
}
HTreeTest.javaHTreeTest.javaimportstatic org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
publicclassHTreeTest{
HTree t;
/**
* Start initializes a test case of HTree
*/
@Before
publicvoid start(){
t=newHTree(1,"one");
HTree a=newHTree(2,"two");
HTree b=newHTree(3,"three");
t.setL(a);
t.setR(b);
}
/**
* testGetBelow tests GetBelow
*/
@Test
publicvoid testGetBelow(){
assertEquals(1,t.getBelow());
assertEquals(0,t.getL().getBelow());
HTree a=newHTree(4,"a");
HTree b=newHTree(5,"b");
t.getL().setL(a);
t.getL().setR(b);
assertEquals(2,t.getBelow());
}
/**
* testGetF tests getF
*/
@Test
publicvoid testGetF(){
assertEquals(1,t.getF());
assertEquals(2,t.getL().getF());
assertEquals(3,t.getR().getF());
}
/**
* testGetS tests getS
*/
@Test
publicvoid testGetS(){
assertEquals("one",t.getS());
assertEquals("two",t.getL().getS());
assertEquals("three",t.getR().getS());
}
/**
* testGetL tests getL
*/
@Test
publicvoid testGetL(){
assertEquals(2,t.getL().getF());
assertEquals(null,t.getL().getL());
}
/**
* testGetR tests getR
*/
@Test
publicvoid testGetR(){
assertEquals(3,t.getR().getF());
assertEquals(null,t.getR().getR());
}
/**
* testIsLeaf tests isLeaf
*/
@Test
publicvoid testIsLeaf(){
assertEquals(false,t.isLeaf());
assertEquals(true,t.getR().isLeaf());
assertEquals(true,t.getL().isLeaf());
}
/**
* testSetL tests setL
*/
@Test
publicvoid testSetL(){
assertEquals(2,t.getL().getF());
t.setL(null);
assertEquals(null,t.getL());
}
/**
* testSetR tests setR
*/
@Test
publicvoid testSetR(){
assertEquals(3,t.getR().getF());
t.setR(null);
assertEquals(null,t.getR());
}
}
Heap$MaxHeapComparator.classpublicsynchronizedclass
Heap$MaxHeapComparator implements java.util.Comparator {
public void Heap$MaxHeapComparator();
public int compare(Comparable, Comparable);
}
Heap$MinHeapComparator.classpublicsynchronizedclass
Heap$MinHeapComparator implements java.util.Comparator {
public void Heap$MinHeapComparator();
public int compare(Comparable, Comparable);
}
Heap.classpublicsynchronizedclass Heap {
int s;
Object[] h;
int maxS;
java.util.Comparator c;
public void Heap(int, java.util.Comparator);
public Object findMax();
public Object removeMax();
public void insert(Object);
public int size();
private void siftUp(int);
private void siftDown(int);
}
Heap.javaHeap.javaimport java.lang.reflect.Array;
import java.util.Comparator;
import java.util.NoSuchElementException;
publicclassHeap<E>{
int s;
Object[] h;
int maxS;
Comparator c;
/**
* Heap takes in the initial size of the heap.
* @param i the integer value of the size of the heap.
*/
publicHeap(int i,Comparator<?super E> comparator){
c=comparator;
s=0;
maxS=i;
h=newObject[i];
}
/**
* findMax returns the largest item of the heap.
* If the heap is empty it will throw a noSuchElementExcepti
on.
* @return E the max object
*/
public E findMax(){
if(s==0){
System.out.println("an error has been thrown because the heap i
s empty");
thrownewNoSuchElementException();
}
return(E) h[0];
}
/**
* removeMax removes the largest item. If the list is empty a
NoSuchElementException is thrown.
* @return the max object
*/
public E removeMax(){
if(s==0){
System.out.println("an error has been thrown because the heap i
s empty");
thrownewNoSuchElementException();
}
E last =(E) h[s-1];
E first =(E) h[0];
h[0]=last;
h[s-1]=null;
s--;
siftDown(0);
return first;
}
/**
* insert inserts an item into the heap and bubbles it into the
correct position.
* @param item that is inserted
*/
publicvoid insert(E item){
if(s==maxS-1){
maxS=maxS*2;
Object[] grownArray =newObject[maxS];
System.arraycopy(h,0, grownArray,0, h.length);
h=grownArray;
}
h[s]=item;
siftUp(s);
s++;
}
/**
* size returns the size of the heap.
* @return the integer size of the heap
*/
publicint size(){
return s;
}
/**
* siftUp, sifts the node at index i up through the heap into th
e correct position.
* @param i the value to begin sifting
*/
privatevoid siftUp(int i)
{
int n=i;
boolean inPlace =false;
if(n==0){
inPlace=true;
}
while(inPlace==false){
int a=(n-1)/2;
E below=(E) h[n];
E above=(E) h[a];
if(c.compare(below,above)>0){
h[n]= above;
h[a]=below;
n=a;
}else{
inPlace=true;
}
}
}
/**
* SiftDown sifts the node at index i down to the correct spot
in the heap.
* @param i the value to begin sifting
*/
privatevoid siftDown(int i)
{
int n=i;
boolean inPlace =false;
while(inPlace==false){
int a=(n*2)+1;
E above=(E) h[n];
E belowL=(E) h[a];
E belowR=(E) h[a+1];
if(belowL==null&& belowR==null){
return;
}
//if neither of the children are null
if(belowL !=null&& belowR !=null){
//compare to the left child
if(c.compare(above,belowL)<0&& c.compare(belowL,belowR)>
=0){
System.out.println("down and to the left!");
h[a]= above;
h[n]=belowL;
n=a;
//compare to the right child
}elseif(c.compare(above,belowR)<0){
System.out.println("down and to the right!");
h[a+1]= above;
h[n]=belowR;
n=a;
//otherwise its in place
}else{
System.out.println("its down in place");
inPlace=true;
}
//if the left child isnt null
}elseif(belowL !=null){
if(c.compare(above, belowL)<0){
h[n]= above;
h[a]=belowL;
n=a;
}else{
inPlace=true;
}
}else{
// if the right child isnt null compare it to the parent
if(c.compare(above,belowR)<0){
h[a+1]= above;
h[n]=belowR;
n=a;
}else{
inPlace=true;
}
}
}
}
/**
* MaxHeapComparator compares two values and prioritizes t
he max value.
* @author tai-lanhirabayashi
*
* @param <E> the comparable object
*/
publicstaticclassMaxHeapComparator<E extendsComparable<E
>>implementsComparator<E>{
@Override
publicint compare(E o1, E o2){
return o1.compareTo(o2);
}
}
/**
* MinHeapComparator compares two values and prioritizes t
he lower value
* @author tai-lanhirabayashi
*
* @param <E> the comparable object
*/
publicstaticclassMinHeapComparator<E extendsComparable<E>
>implementsComparator<E>{
@Override
publicint compare(E o1, E o2){
return(-1* o1.compareTo(o2));
}
}
}
PriorityQueueTest.classpublicsynchronizedclass
PriorityQueueTest {
PriorityQueue p;
public void PriorityQueueTest();
public void start();
public void testPeek();
public void testRemove();
public void testSize();
public void testEmpty();
}
PriorityQueueTest.javaPriorityQueueTest.javaimportstatic org.j
unit.Assert.*;
import java.util.Comparator;
import org.junit.Before;
import org.junit.Test;
publicclassPriorityQueueTest{
PriorityQueue p;
/**
* Start initialized the program, with a queue of 1,2,3,4 and a
max priority.
*/
@Before
publicvoid start(){
Comparator<Integer> c =newHeap.MaxHeapComparator();
p=newPriorityQueue(10, c);
p.add(1);
p.add(2);
p.add(3);
p.add(4);
}
/**
* testPeek tests the peek function.
*/
@Test
publicvoid testPeek(){
assertEquals(4, p.peek());
p.remove();
assertEquals(3, p.peek());
p.remove();
assertEquals(2, p.peek());
p.remove();
assertEquals(1, p.peek());
p.remove();
assertEquals(null, p.peek());
}
/**
* restRemove tests the remove function.
*/
@Test
publicvoid testRemove(){
assertEquals(4, p.remove());
assertEquals(3, p.remove());
assertEquals(2, p.remove());
assertEquals(1, p.remove());
assertEquals(null, p.remove());
}
/**
* testSize tests the size function.
*/
@Test
publicvoid testSize(){
assertEquals(4, p.size());
p.remove();
assertEquals(3, p.size());
p.remove();
assertEquals(2, p.size());
p.remove();
assertEquals(1, p.size());
p.remove();
assertEquals(0, p.size());
p.add(9);
assertEquals(1, p.size());
}
/**
* testEmpty tests the isEmpty function of priorityQueue.
*/
@Test
publicvoid testEmpty(){
assertFalse(p.isEmpty());
p.remove();
assertFalse(p.isEmpty());
p.remove();
assertFalse(p.isEmpty());
p.remove();
assertFalse(p.isEmpty());
p.remove();
assertTrue(p.isEmpty());
p.add(5);
assertFalse(p.isEmpty());
}
}
BSTMap.classpublicsynchronizedclass BSTMap extends Map {
nObject obj;
BSTMap left;
BSTMap right;
int s;
BSTMap parent;
public void BSTMap(Object, Object);
public void setParent(BSTMap);
public BSTMap getParent();
public void setLeft(BSTMap);
public void setRight(BSTMap);
public BSTMap getLeft();
public BSTMap getRight();
boolean isLeaf();
}
BSTMap.javaBSTMap.java
publicclassBSTMap<K,V>extendsMap{
nObject obj;
BSTMap<K,V> left;
BSTMap<K,V> right;
int s;
BSTMap<K,V> parent;
/**
* BSTMap creates a node with a K key and V value.
* @param ke the K value
* @param va the V value
*/
publicBSTMap(K ke, V va){
obj=new nObject(ke,va);
left=null;
right=null;
parent=null;
}
/**
* setParent sets the BSTMap which is this nodes parent.
* @param p the parent
*/
publicvoid setParent(BSTMap<K,V> p){
parent=p;
}
/**
* getParent returns the parent of this node.
* @return BSTMap that is this nodes parent.
*/
publicBSTMap<K,V> getParent(){
return parent;
}
/**
* setLeft sets the BSTMap left child.
*
* @param child BSTMap that is this nodes child.
*/
publicvoid setLeft(BSTMap<K,V> child){
left=child;
if(child!=null){
left.setParent(this);
}
}
/**
* setRight sets the this nodes BSTMap child.
* @param child BSTMap that is this nodes child.
*/
publicvoid setRight(BSTMap<K,V> child){
right=child;
if(child!=null){
right.setParent(this);
}
}
/**
* getLeft returns this nodes left BSTMap child.
* @return BSTMap this nodes left child
*/
publicBSTMap<K,V> getLeft(){
return left;
}
/**
* getRight returns this nodes right BSTMap child.
* @return BSTMap this nodes right child
*/
publicBSTMap<K,V> getRight(){
return right;
}
/**
* isLeaf checks if the node is a leaf node by checking if it ha
s children.
*
* It returns true for leaf, false for if it has children.
* @return boolean if the node is a leaf node.
*/
boolean isLeaf(){
if(getLeft()==null&& getRight()==null){
returntrue;
}
returnfalse;
}
}
BinaryTreeTest.classpublicsynchronizedclass BinaryTreeTest {
BinaryTree t;
public void BinaryTreeTest();
public void before();
public void testSetup();
public void testGetLeft();
public void testGetRight();
public void isLeaf();
public void setLeft();
public void setRight();
public void setValue();
}
BinaryTreeTest.javaBinaryTreeTest.javaimportstatic org.junit.A
ssert.*;
import org.junit.Before;
import org.junit.Test;
/**
* BinaryTreeTest tests to see if Binary Tree functions as expect
ed.
* @author tai-lanhirabayashi
*
*/
publicclassBinaryTreeTest{
BinaryTree t;
/**
* before sets up a base case.
*/
@Before
publicvoid before(){
t=newBinaryTree(null,"head",null);
t.setLeftChild(newBinaryTree(null,"second",null));
t.getLeftChild().setLeftChild(newBinaryTree(null,"third",
null));
}
/**
* testSetup makes sure the test has been initialized.
*/
@Test
publicvoid testSetup(){
assertEquals(t.getValue(),"head");
}
/**
* tests the getLeft function
*/
@Test
publicvoid testGetLeft(){
assertEquals(t.getLeftChild().getValue(),"second");
}
/**
* Tests the get right function
*/
@Test
publicvoid testGetRight(){
assertEquals(t.getRightChild(),null);
}
/**
* Tests the isLeaf function.
*/
@Test
publicvoid isLeaf(){
assertEquals(t.getLeftChild().getLeftChild().isLeaf(),true);
}
/**
* Tests the setLeft function
*/
@SuppressWarnings("unchecked")
@Test
publicvoid setLeft(){
t.setLeftChild(newBinaryTree(null,"replace",null));
assertEquals(t.getLeftChild().getValue(),"replace");
}
/**
* tests the setRightChild function
*/
@SuppressWarnings("unchecked")
@Test
publicvoid setRight(){
t.setRightChild(newBinaryTree(null,"right",null));
assertEquals(t.getRightChild().getValue(),"right");
}
/**
* Tests the setValue function.
*/
@Test
publicvoid setValue(){
t.getLeftChild().setValue("reset");
assertEquals(t.getLeftChild().getValue(),"reset");
}
}
ArithmeticExpressionTest.classpublicsynchronizedclass
ArithmeticExpressionTest {
ArithmeticExpression a;
public void ArithmeticExpressionTest();
public void startUp() throws java.text.ParseException;
public void testExceptions();
public void testToString();
public void testEval();
public void testVar() throws java.rmi.NotBoundException,
java.text.ParseException;
public void testPostFix();
public void testWithoutSpaces() throws
java.text.ParseException;
}
ArithmeticExpressionTest.javaArithmeticExpressionTest.javaim
portstatic org.junit.Assert.*;
import java.rmi.NotBoundException;
import java.text.ParseException;
import org.junit.Before;
import org.junit.Test;
/**
* ArithmeticExpressionTest tests the functionality of Arithmeti
cExpression.
*** Note, the Program includes postFix() which returns a postfi
x String of the equation.
*** It can also handle strings with or without spaces.
*
*
* @author tai-lan hirabayashi
*
*/
publicclassArithmeticExpressionTest{
ArithmeticExpression a;
/**
* StartUp sets up the base case scenario.
* @throws ParseException if the equation is not valid.
*/
@Before
publicvoid startUp()throwsParseException{
a=newArithmeticExpression("3 + 4 * 2");
}
/**
* testExceptions tests the programs thrown exceptions.
*/
@Test
publicvoid testExceptions(){
boolean errorThrown =false;
try{
a=newArithmeticExpression("3 + * 2");
}catch(ParseException e){
errorThrown=true;
}
assert(errorThrown);
errorThrown=false;
try{
a.setVariable("y",2);
}catch(NotBoundException e){
errorThrown=true;
}
assert(errorThrown);
}
/**
* testToString tests the toString method of the ArithmeticEx
pression
*/
@Test
publicvoid testToString(){
System.out.println("this is toString: "+ a.toString(a.t));
assertEquals(a.toString(a.t),"((2*4)+3)");
}
/**
* testEval tests the evaluate method of ArithmeticExpression
*/
@Test
publicvoid testEval(){
assertEquals(a.evaluate(a.t),11);
}
/**
* testVar tests the setVariable function of ArithmeticExpress
ion
* by checking how a variable is handled.
* @throws NotBoundException
* @throws ParseException if the equation is not valid.
*/
@Test
publicvoid testVar()throwsNotBoundException,ParseException{
a=newArithmeticExpression("2 + 3 * x");
assertEquals(a.evaluate(a.t),2);
a.setVariable("x",2);
assertEquals(a.evaluate(a.t),8);
}
/**
* Tests the postFix() method.
*/
@Test
publicvoid testPostFix(){
assertEquals(a.toPostfixString(a.t),"3 4 2 * +");
}
@Test
publicvoid testWithoutSpaces()throwsParseException{
a=newArithmeticExpression("2+3*x");
assertEquals(a.evaluate(a.t),2);
}
}
nObject.classpublicsynchronizedclass nObject {
Object key;
Object value;
public void nObject(Object, Object);
public Object getKey();
public Object getValue();
public void changeKey(Object);
public void changeValue(Object);
}
nObject.javanObject.java
publicclass nObject<K,V>{
K key;
V value;
/**
* nObject creates a new nObject object with a K,V values he
ld.
* @param ky the K key value
* @param val the V value value.
*/
public nObject (K ky, V val){
key=ky;
value=val;
}
/**
* getKey returns the K key.
* @return K, the key
*/
public K getKey(){
return key;
}
/**
* getValue returns the V value.
* @return V value
*/
public V getValue(){
return value;
}
/**
* changeK allows the user to pass in a new K key.
* @param ky K to be changed to.
*/
publicvoid changeKey(K ky){
key=ky;
}
/**
* changeValue allows the value to be changed.
* @param val the new V value.
*/
publicvoid changeValue(V val){
value=val;
}
}
BSTMapTest.classpublicsynchronizedclass BSTMapTest {
BSTMap m;
public void BSTMapTest();
public void startUp();
public void testGetLeft();
public void testGetRight();
public void testGetParent();
public void testIsLeaf();
public void testSetLeft();
public void testSetRight();
public void testSetParent();
}
BSTMapTest.javaBSTMapTest.javaimportstatic org.junit.Assert
.*;
import org.junit.Before;
import org.junit.Test;
publicclassBSTMapTest{
BSTMap m;
/**
* startUp creates a new instance of BSTMap.
*/
@Before
publicvoid startUp(){
m=newBSTMap(1,"one");
}
/**
* testGetLeft tests getLeft().
*
* It tests when it doesnt exist, when it does exist, when it ha
s been changed, and when it has been removed.
*/
@Test
publicvoid testGetLeft(){
assertEquals(null, m.getLeft());
m.setRight(newBSTMap(3,"three"));
assertEquals(null, m.getLeft());
BSTMap child=newBSTMap(2,"two");
BSTMap a=newBSTMap(1,"a");
m.setLeft(child);
assertEquals(child, m.getLeft());
m.setLeft(a);
assertEquals(a, m.getLeft());
m.setLeft(null);
assertEquals(null, m.getLeft());
}
/**
* testGetRight tests getRight().
*
* It tests when it doesnt exist, when it does exist, and when i
t has been removed.
*/
@Test
publicvoid testGetRight(){
assertEquals(null, m.getRight());
m.setLeft(newBSTMap(2,"two"));
assertEquals(null, m.getRight());
BSTMap child =newBSTMap(3,"three");
BSTMap a=newBSTMap(1,"a");
m.setRight(child);
assertEquals(child, m.getRight());
m.setRight(a);
assertEquals(a, m.getRight());
m.setRight(null);
assertEquals(null, m.getRight());
}
/**
* testGetParent tests getParent()
*
* It tests when there is a parent, when there is not a parent.
*/
@Test
publicvoid testGetParent(){
assertEquals(null, m.getParent());
m.setLeft(newBSTMap(2,"two"));
assertEquals(null, m.getParent());
BSTMap child =newBSTMap(3,"three");
m.setRight(child);
assertEquals(m, child.getParent());
}
/**
* testIsLeaf tests to see if a node is a leaf.
*
* It tests when it has no children, when it has a left child, a
right child, both, and when they have been removed.
*/
@Test
publicvoid testIsLeaf(){
assertTrue(m.isLeaf());
m.setLeft(newBSTMap(2,"two"));
assertFalse(m.isLeaf());
m.setRight(newBSTMap(3,"three"));
assertFalse(m.isLeaf());
m.setLeft(null);
assertFalse(m.isLeaf());
m.setRight(null);
assertTrue(m.isLeaf());
}
/**
* testSetLeft tests setLeft()
*
*/
@Test
publicvoid testSetLeft(){
assertEquals(null, m.getLeft());
BSTMap child=newBSTMap(2,"two");
m.setLeft(child);
m.setRight(newBSTMap(3,"three"));
assertEquals(child,m.getLeft());
m.setLeft(null);
assertEquals(null,m.getLeft());
}
/**
* testSetRight tests setRight
*/
@Test
publicvoid testSetRight(){
BSTMap child=newBSTMap(2,"two");
BSTMap a=newBSTMap(1,"a");
assertEquals(null, a.getRight());
a.setRight(child);
assertEquals(child, a.getRight());
a.setRight(null);
assertEquals(null, a.getRight());
}
/**
* testSetParent tests setParent
*/
@Test
publicvoid testSetParent(){
BSTMap child=newBSTMap(2,"two");
BSTMap a=newBSTMap(1,"a");
assertEquals(null, a.getParent());
a.setParent(child);
assertEquals(child, a.getParent());
a.setParent(null);
assertEquals(null, a.getParent());
}
}
HTree.classpublicsynchronizedclass HTree {
private String s;
private int f;
HTree l;
HTree r;
public void HTree(int, String);
public void setL(HTree);
public void setR(HTree);
public HTree getL();
public HTree getR();
public String getS();
public int getF();
public boolean isLeaf();
public int getBelow();
}
HTree.javaHTree.java
publicclassHTree<E extendsComparable<E>>{
privateString s;
privateint f;
HTree l;
HTree r;
/**
* HTree creates a HTree object containing a int frequency an
d a String str.
* @param frequency the integer frequency of the str
* @param str the str value of this HTree
*/
publicHTree(int frequency,String str){
s=str;
f=frequency;
l=null;
r=null;
}
/**
* setL sets the left HTree value
* @param left the HTree that is the left child of this node
*/
publicvoid setL(HTree left){
l=left;
}
/**
* setR sets the right HTree child value
* @param right the HTree that is the right child of this node
*/
publicvoid setR(HTree right){
r=right;
}
/**
* getL returns the left child of this node.
* @return HTree the left child.
*/
publicHTree getL(){
return l;
}
/**
* getR returns the right child of this node.
* @return HTree the right child.
*/
publicHTree getR(){
return r;
}
/**
* getS returns the string value associated with this node
* @return String the value of this node
*/
publicString getS(){
return s;
}
/**
* getF returns the frequency value associated with this node.
* @return the int frequency value associated with this node.
*/
publicint getF(){
return f;
}
/**
* isLeaf returns boolean if this node is a leaf.
* @return boolean wether this node is a leaf.
*/
publicboolean isLeaf(){
if(l==null&&r==null){
returntrue;
}
returnfalse;
}
/**
* getBelow recursively finds how many children this node h
as.
*
* **this does not handle trees with only one child (as this do
es not occur in a huffmanTree)
* @return the int number height
*/
publicint getBelow(){
if(isLeaf()){
return0;
}else{
int a=1+l.getBelow();
int b=1+r.getBelow();
if(a>b){
System.out.println("returning a: "+ a);
return a;
}
System.out.println("returning b"+ b);
return b;
}
}
}
HeapTest.classpublicsynchronizedclass HeapTest {
Heap h;
Heap min;
public void HeapTest();
public void start();
public void testFindMax();
public void testRemoveMax();
public void testSize();
public void testMin();
}
HeapTest.javaHeapTest.javaimportstatic org.junit.Assert.*;
import java.util.Comparator;
import org.junit.Before;
import org.junit.Test;
publicclassHeapTest{
Heap h;
Heap min;
/**
* start creates a test case of heap both min and max compara
tor.
*/
@Before
publicvoid start(){
Comparator<Integer> c =newHeap.MaxHeapComparator<Intege
r>();
Comparator<Integer> m =newHeap.MinHeapComparator<Intege
r>();
min=newHeap(10,m);
min.insert(1);
min.insert(2);
min.insert(3);
min.insert(4);
h=newHeap(10,c);
System.out.println("this is 1");
h.insert(1);
System.out.println(h.h[0]);
System.out.println("this is 2");
h.insert(2);
System.out.println(h.h[0]+","+h.h[1]);
System.out.println("this is 3");
h.insert(3);
System.out.println(h.h[0]+","+h.h[1]+","+h.h[2]);
System.out.println("this is 4");
h.insert(4);
System.out.println(h.h[0]+","+h.h[1]+","+h.h[2]+","+h.h[3]);
}
/**
* testFindMax tests the findMax function
*/
@Test
publicvoid testFindMax(){
assertEquals(4, h.findMax());
assertEquals(4, h.removeMax());
assertEquals(3, h.findMax());
assertEquals(1, min.findMax());
assertEquals(1, min.removeMax());
assertEquals(2, min.findMax());
}
/**
* testRemoveMax tests the remove max function
*/
@Test
publicvoid testRemoveMax(){
assertEquals(4, h.findMax());
assertEquals(4,h.removeMax());
assertEquals(3, h.findMax());
assertEquals(3,h.removeMax());
assertEquals(2,h.removeMax());
assertEquals(1,h.removeMax());
assertEquals(0,h.size());
assertEquals(1, min.findMax());
}
/**
* testSize tests the size function of heap.
*/
@Test
publicvoid testSize(){
assertEquals(4, h.size());
int o=(Integer) h.removeMax();
assertEquals(3, h.size());
h.insert(o);
assertEquals(4, h.size());
h.removeMax();
h.removeMax();
h.removeMax();
h.removeMax();
assertEquals(0, h.size());
assertEquals(4, min.size());
}
/**
* testMin tests the minSort comparator.
*/
@Test
publicvoid testMin(){
assertEquals(4, min.size());
assertEquals(1,min.removeMax());
assertEquals(2,min.removeMax());
assertEquals(3,min.removeMax());
assertEquals(4,min.removeMax());
}
}
HuffmanTree$CountPair.classsynchronizedclass
HuffmanTree$CountPair {
int _count;
String _text;
private void HuffmanTree$CountPair(HuffmanTree, String,
int);
}
HuffmanTree$CountPairTreeComparator.classsynchronizedclass
HuffmanTree$CountPairTreeComparator implements
java.util.Comparator {
private void
HuffmanTree$CountPairTreeComparator(HuffmanTree);
public int compare(BinaryTree, BinaryTree);
}
HuffmanTree.classpublicsynchronizedclass HuffmanTree {
java.io.File current;
BSTMap _lookupTable;
BinaryTree _huffmanTree;
public void HuffmanTree();
publicstatic HuffmanTree newTreeFromFile(java.io.File)
throws java.io.FileNotFoundException;
publicstatic HuffmanTree
newTreeFromCompressedFile(java.io.File) throws
java.io.FileNotFoundException;
private void buildFromFile(java.io.File) throws
java.io.FileNotFoundException;
private void buildTreeFromMap(PriorityQueue);
private void buildFromCompressedFile(java.io.File) throws
java.io.FileNotFoundException;
public void saveCompressedFile(java.io.File);
public void saveExpandedFile(java.io.File);
public String encode(String);
public String decode(String);
}
HuffmanTree.javaHuffmanTree.javaimport java.io.File;
import java.io.FileNotFoundException;
import java.util.Comparator;
import java.util.Scanner;
import java.util.Set;
/**
* This class implements the basic functionality of Huffman co
mpression and expansion.
*
* @author C. Andrews
*
*/
publicclassHuffmanTree{
File current;
BSTMap<String,String> _lookupTable =newBSTMap<String,Str
ing>(null,null);
BinaryTree<CountPair> _huffmanTree;
/**
* This is a factory method for reading in a fresh text file to i
nitialize the Huffman tree.
*
* @param file the document to use for the code frequencies
* @return a HuffmanTree containing the Huffman codes bas
ed on the frequencies observed in the document
* @throws FileNotFoundException
*/
publicstaticHuffmanTree newTreeFromFile(File file)throwsFile
NotFoundException{
HuffmanTree tree =newHuffmanTree();
tree.buildFromFile(file);
return tree;
}
/**
* This is a factory method that builds a new HuffmanTree fr
om a compressed file.
*
* @param file a file that has been compressed with a Huffma
n tool
* @return a new HuffmanTree containing the codes for deco
ding the file
* @throws FileNotFoundException
*/
publicstaticHuffmanTree newTreeFromCompressedFile(File file
)throwsFileNotFoundException{
// TODO implement this
}
/**
* This method builds the Huffman tree from the input file.
*
* @param file the file to use to construct the Huffman tree
* @throws FileNotFoundException
*/
privatevoid buildFromFile(File file)throwsFileNotFoundExcepti
on{
current=file;
// read file and build the map of the character frequencies
Map<String,Integer> freqMap =newBSTMap<String,Integer>();
Scanner scanner =newScanner(file);
scanner.useDelimiter("");
String character;
while(scanner.hasNext()){
character = scanner.next();
Integer count = freqMap.get(character);
if(count ==null){
count =Integer.valueOf(0);
}
freqMap.put(character, count+1);
}
// for each key, make a tree and load it into the priority queue
PriorityQueue<BinaryTree<CountPair>> treeQueue =newPriorit
yQueue<BinaryTree<CountPair>>(freqMap.keySet().size(),new
CountPairTreeComparator());
BinaryTree<CountPair> tmpTree;
for(String key: freqMap.keySet()){
int frequency = freqMap.get(key);
tmpTree =newBinaryTree<CountPair>(null,newCountPa
ir(key, frequency),null);
treeQueue.add(tmpTree);
}
// while the size of the priority queue is greater than 1, combine
the top items into a tree and put them back in the priority queue
BinaryTree<CountPair> tree1, tree2;
int newFrequency;
String newText;
while(treeQueue.size()>1){
tree1 = treeQueue.remove();
tree2 = treeQueue.remove();
// If the height of the second tree is less than the height of the fi
rst,
// or the heights are the same and tree2 precedes tree1 alphabeti
cally, swap them so
// the smaller/earlier tree is put on the left
if(tree1.getValue()._text.length()> tree2.getValue()._text.length
()
||( tree1.getValue()._text.length()== tree2.getValue()._text.lengt
h()
&& tree1.getValue()._text.compareTo(tree2.getValue()._text)>0
)){
tmpTree = tree1;
tree1 = tree2;
tree2 = tmpTree;
}
// create a new tree combining the two smaller trees, computing
a new frequency that is the sum of the
// children frequencies and a new text that is the appended comb
ination of the children's text
newFrequency = tree1.getValue()._count + tree2.getVal
ue()._count;
newText = tree1.getValue()._text + tree2.getValue()._te
xt;
tmpTree =newBinaryTree<CountPair>(tree1,newCountP
air(newText, newFrequency), tree2);
treeQueue.add(tmpTree);
}
// pull the completed tree from the priority queue
BinaryTree<CountPair> tree = treeQueue.remove();
// create map of symbols to code lengths using the tree
Map<String,Integer> codeLengthMap =newMap<String,Integer>
();
// TODO implement this part
PriorityQueue pq=newPriorityQueue(setC.size(),new treeCompa
rator());
buildTreeFromMap(pq);
}
privatevoid buildTreeFromMap(PriorityQueue q){
// TODO Auto-generated method stub
}
/**
* Builds the tree using information found in a compressed fil
e.
*
* The table is the first thing we find in the file. The first pie
ce of data is the length
* of the table (L). This is followed by L pairs of character an
d code length pairs.
*
* @param file the file to read the Huffman code from.
*/
privatevoid buildFromCompressedFile(File file)throwsFileNotF
oundException{
// TODO implement this
}
/**
* Read the original file and compress it using the Huffman cod
es, writing the result
* into the output file.
*
* @param outputFile the output file
*/
publicvoid saveCompressedFile(File outputFile){
// TODO implement this
}
/**
* Read the compressed file that initialized this object and wr
ite the decoded version out
* into the output file.
*
* @param outputFile the destination file for the uncompress
ed file.
*/
publicvoid saveExpandedFile(File outputFile){
// TODO implement this
}
/**
* This method reads in a String of text and returns a String o
f 0s and 1s corresponding to the Huffman code stored in this tre
e.
* @param text the text to be encoded
* @return a String representation of the Huffman code
*/
publicString encode(String text){
StringBuilder builder =newStringBuilder();
String tmp;
for(int i =0; i < text.length(); i++){
tmp = _lookupTable.get(String.valueOf(text.charAt(i)));
builder.append(tmp);
}
return builder.toString();
}
/**
* This method reads in a String representation of a Huffman
code corresponding to this Huffman tree and decodes it.
* @param text a String representation of the a Huffman code
d message
* @return the original text
*/
publicString decode(String text){
StringBuilder builder =newStringBuilder();
BinaryTree<CountPair> current = _huffmanTree;
for(int i =0; i < text.length(); i++){
char c = text.charAt(i);
if(c =='0'){
current = current.getLeftChild();
}elseif(c =='1'){
current = current.getRightChild();
}else{
thrownewRuntimeException("Encountered unexpected character
in coded String");
}
if(current.isLeaf()){
builder.append(current.getValue()._text);
current = _huffmanTree;
}
}
return builder.toString();
}
privateclassCountPair{
int _count;
String _text;
privateCountPair(String text,int count){
_text = text;
_count = count;
}
}
privateclassCountPairTreeComparatorimplementsComparator<B
inaryTree<CountPair>>{
@Override
publicint compare(BinaryTree<CountPair> t1,BinaryTree<Coun
tPair> t2){
CountPair p1 = t1.getValue();
CountPair p2 = t2.getValue();
if(p1._count != p2._count){
return p2._count - p1._count;
}elseif(p1._text.length()!= p2._text.length()){
return-p1._text.length()- p2._text.length();
}else{
return p1._text.compareTo(p2._text);
}
}
}
}
nObjectTest.classpublicsynchronizedclass nObjectTest {
nObject o;
public void nObjectTest();
public void setUp();
public void testChangeKey();
public void testChangeValue();
public void testGetKey();
public void testGetValue();
}
nObjectTest.javanObjectTest.javaimportstatic org.junit.Assert.*
;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
publicclass nObjectTest {
nObject o;
/**
* setUp sets up the test.
*/
@Before
publicvoid setUp(){
o=new nObject("one",1);
}
/**
* tests the change Key function
*/
@Test
publicvoid testChangeKey(){
assertEquals("one", o.getKey());
o.changeKey("two");
assertEquals("two", o.getKey());
}
/**
* tests the change Value function
*/
@Test
publicvoid testChangeValue(){
assertEquals(1, o.getValue());
o.changeValue(2);
assertEquals(2, o.getValue());
}
/**
* testGetKey tests the getKey method
*/
@Test
publicvoid testGetKey(){
assertEquals("one", o.getKey());
o.changeKey("two");
assertEquals("two", o.getKey());
}
/**
* testGetValue tests get Value
*/
@Test
publicvoid testGetValue(){
assertEquals(1, o.getValue());
o.changeValue(2);
assertEquals(2, o.getValue());
}
}
MapTest.classpublicsynchronizedclass MapTest {
Map m;
public void MapTest();
public void start();
public void testContainsKey();
public void testGet();
public void testKeySet();
public void testPut();
public void testRemove();
}
MapTest.javaMapTest.javaimportstatic org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
publicclassMapTest{
Map m;
/**
* start() creates an initial map to test.
*/
@Before
publicvoid start(){
m=newMap();
}
/**
* testContainsKey tests the containsKey function.
* It tests when there are more than one object, one object,
* when the object is contained, and when the object is not co
ntained.
*/
@Test
publicvoid testContainsKey(){
assertFalse(m.containsKey(5));
m.put(5,"five");
m.put(4,"four");
assertTrue( m.containsKey(5));
m.remove(5);
assertFalse(m.containsKey(5));
m.remove(4);
assertFalse(m.containsKey(4));
}
/**
* testGet tests the get function of map.
*
* It tests when there are no objects, when there is an object,
and when there are more than one objects.
*/
@Test
publicvoid testGet(){
assertEquals(null, m.get(5));
m.put(5,"five");
assertEquals("five",m.get(5));
m.put(4,"four");
assertEquals("five",m.get(5));
}
/**
* testKeySet tests keySet.
*/
@Test
publicvoid testKeySet(){
assertEquals(true, m.keySet().isEmpty());
m.put(5,"five");
assertEquals(false, m.keySet().isEmpty());
assertEquals(true, m.keySet().contains(5));
}
/**
* testPut tests the put method of map.
*/
@Test
publicvoid testPut(){
assertEquals(null, m.get(5));
m.put(5,"five");
assertEquals("five",m.get(5));
m.put(5,"changed");
m.put(6,"six");
assertEquals("changed",m.get(5));
assertEquals("six",m.get(6));
}
/**
* testRemove tests map's remove function
*
* It tests if it can remove something that isnt in map, and re
moval of objects not in order.
*/
@Test
publicvoid testRemove(){
assertEquals(null, m.remove("a"));
m.put(5,"five");
m.put(4,"four");
m.put(3,"three");
assertEquals("three", m.remove(3));
assertEquals("five", m.remove(5));
assertEquals("four", m.remove(4));
}
}
.project
assignment 8
org.eclipse.jdt.core.javabuilder
org.eclipse.jdt.core.javanature
1/1/13 10:10 PMCS 211 Homework Seven — Fall 2012
Page 1 of
3http://web.cs.mtholyoke.edu/~candrews/cs211/homework/hw7.
html
CS 212 — Homework Seven
Huffman Codes
Due: 13 November 2012, 11:59p
Worth: 90 points
The Task
This week you are going to implement a new data structure and
the main Huffman tree. Next week we
will finish this off with a full application for compressing and
decompressing text files.
Part one: PriorityQueue [20 pts]
As I said in class, I redesigned final product of this project, so
we need to redo the PriorityQueue and the
Heap. This is actually good practice for you because refactoring
code to meet changing specifications is a
common occurrence in software development. We basically
want to have a different level of control, so
we are going to change our classes to be closer to the
PriorityQueue provided in the Java API. The new
interface for PriorityQueue looks like this:
public PriorityQueue(int initialCapacity,Comparator<? super E>
comparator)
This is the constructor. It should initialize the heap using the
initialCapacity. The comparator is the tool that will
allow us to change how priority is calculated for various inputs.
public E peek()
This returns the next item without removing it. This returns null
if the queue is empty.
E remove()
This removes the first item from the queue.
void add(E item)
This adds item to the queue
boolean isEmpty()
Obviously, this says if the queue is empty or not.
int size()
This should return the size of the queue.
The main difference is the addition of the Comparator.
Comparators are classes that provide the same
functionality as compareTo(). You will use this instead of the
compareTo method for comparing items in the
queue. We can write different comparators to give us high value
priority, low value priority, or more
complex variations (which is why we need to do this).
Doing this will mean that the wrapper class you wrote for the
last assignment is no longer needed, the
priority will be supplied in a different way. You may be
wondering about the Comparator<? super E>. We
are specifying that our Comparator is capable of comparing two
objects of type E. The ? says that it can
compare two Es, or E is a subclass of the class that the
Comparator can handle.
You will, of course, need to adjust the Heap as well to work
with this new PriorityQueue. Add the
Comparator to the constructor and update siftup and siftdown to
use it. Also, write two static, public
inner classes on the Heap called MaxHeapComparator and
MinHeapComparator. These comparators will provide
the normal functionality of min and max by calling the
compareTo methods on the stored items (i.e., they
will only work for objects that implement Comparable.
Part two: Map [30 pts]
Next, we need a new data structure. We are going to build this
in two pieces so that we can reuse the
http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.ht
ml
1/1/13 10:10 PMCS 211 Homework Seven — Fall 2012
Page 2 of
3http://web.cs.mtholyoke.edu/~candrews/cs211/homework/hw7.
html
interface later. So, the first this you should build is an interface
called Map<K extends Comparable<K>,V>.
The interface should look like this:
void put(K key, V value)
This should load the value value into the map at the location
associated with the key, replacing any preexisting value
already associated with the key.
V get(K key)
This should fetch the value V associated with the key key, or
null, if no match can be found.
boolean containsKey(K key)
This will report if there is a value associated with the value key
in the map.
V remove(K key)
This method should remove the entry associated with key and
return the associated value. Return null if the key is
not found.
Set<K> keySet()
This method should return a Set of all available keys in the
map. You may use the java.util.TreeSet class to return
these. You can build these on the fly using a traversal, or
collect them as new keys are added to the map.
Of course, since this is just the interface, you will need to
implement an actual instance so that you can
use it. This instance should be called BSTMap<K,V>.
Obviously, this will use a binary search tree to actually
implement the methods described above. While one perfectly
valid implementation choice would be to
create a separate binary search tree class and just use it to
implement the described methods, it can
force you to jump through some hoops to make methods like get
and containsKey to work properly. So
instead, you can build the binary search tree structure directly
into your implementation of BSTMap.
When constructing the underlying BST, you will need to create
some form of node structure that will hold
both the key and the value. You will, of course, need to adjust
the pseudocode that we walked through in
class to work directly with the key values. It is important that
these nodes are not visible outside of the
class. The other major aspect of this design is whether you use
an array or links in the nodes to
implement the actual tree. I encourage you to use the linked
version as we will be building on this class
later and will want it to be easy to move nodes around.
Part three: The Huffman tree [40 pts]
Once you have built your map, you will have enough tools to
actually build the Huffman tree. The tree
should be in a class called HuffmanTree. The interface should
look like this:
static HuffmanTree newTreeFromFile(File file)
This is a static factory method that creates a new Huffman tree.
In essence, this just creates the new object and
calls buildFromFile on it. This should throw a
FileNotFoundException when appropriate.
private void buildFromFile(File file)
This reads in an unencoded file and builds the Huffman tree
based on the character frequencies. This should throw a
FileNotFoundException when appropriate.
String encode(String text)
This method takes in some plain text and returns the encoded
version as a String of 1's and 0's.
String decode(String text)
This method takes in a String of 1's and 0's and returns a
decoded raw text version.
For this assignment I am introducing you to a new Java design
pattern called the "factory method".
Factory methods are methods (usually static) that return new
instances of a class. We typically use them
when there is some complex initialization that needs to be
performed or we have more than one way in
which we want an object to be created. In this case, we are
paving the way for future development. The
factory method should just create a new HuffmanTree and then
call buildFromFile on it.
To actually build the tree, you should start by reading the seed
file one character at a time, using the Map
to keep track of the frequencies of each character. Once the file
has been consumed, you will use your
PriorityQueue to to build the Huffman tree.
You will want to create a private inner node class that holds a
frequency and a String. Since we want to
assemble everything into a binary tree structure (it will be a
heap, but we won't use the Heap class for it),
also include left and right children. Call this class HTree. Write
a constructor that sets all of the fields at
1/1/13 10:10 PMCS 211 Homework Seven — Fall 2012
Page 3 of
3http://web.cs.mtholyoke.edu/~candrews/cs211/homework/hw7.
html
once.
For each character you read in, create an HTree wrapper for it
and its frequency and put it in the
PriorityQueue. The general algorithm for building the Huffman
tree goes like this:
Remove the two trees with the lowest frequency from the queue
Use these two trees as the left and right children of a new tree
with a root node that has the
frequency of the two children combined.
Return this tree to the queue
Repeat until there is only one tree — this is the Huffman tree
To make this work, you will want to write a Comparator that
uses the lowest frequency as the highest
priority. Unfortunately, this algorithm does not create unique
trees. We would like to build a canonical
Huffman tree. In order to do that, we will add some more rules.
When we have two trees that have the
same frequency, we will take the shorter one first. When we
have two trees of the same complexity and
the same length, we will use alphabetical order to determine
priority (e.g., 'a' comes before 'b'). In
addition, when we build our subtrees, the shorter tree goes on
the left. If the trees are the same length,
the first alphabetically goes of the left (note that this is true
regardless of frequency).
Once the tree is fully constructed, you should create a second
map that stores the final codes for each
character. The tree and this map should be the two data
structures that you keep around after the
construction process. For encoding, you will use the map to
lookup each character, and for decoding, you
will use the tree to find the decoded characters.
I want you to notice that the two methods, encode and decode
are really only for testing. They transform
the data into Strings of 1s and 0s, which is certainly not a
compressed form for the data.
Turning the assignment in...
Commented source files and tests should be put into a single
directory, zipped, tarred or jarred, and
submitted online into your course dropbox on ella (I only want
source files, I do not want any class files).
Please name your files cs211_pid_hw7.suffix, where pid is your
Mount Holyoke email account name and
suffix is the appropriate suffix for your archive format.
Last modified: Mon Dec 17 17:11:21 EST 2012
1/1/13 10:08 PM
Page 1 of
3http://web.cs.mtholyoke.edu/~candrews/cs211/examples/Huffm
anTree.html
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Comparator;
import java.util.Scanner;
import java.util.Set;
/**
* This class implements the basic functionality of Huffman
compression and expansion.
*
* @author C. Andrews
*
*/
public class HuffmanTree {
Map<String, String> _lookupTable = new BSTMap<String,
String>();
BinaryTree<CountPair> _huffmanTree;
/**
* This is a factory method for reading in a fresh text file to
initialize the Huffman tree.
*
* @param file the document to use for the code frequencies
* @return a HuffmanTree containing the Huffman codes based
on the frequencies observed in the document
* @throws FileNotFoundException
*/
public static HuffmanTree newTreeFromFile(File file) throws
FileNotFoundException{
HuffmanTree tree = new HuffmanTree();
tree.buildFromFile(file);
return tree;
}
/**
* This is a factory method that builds a new HuffmanTree
from a compressed file.
*
* @param file a file that has been compressed with a Huffman
tool
* @return a new HuffmanTree containing the codes for
decoding the file
* @throws FileNotFoundException
*/
public static HuffmanTree newTreeFromCompressedFile(File
file) throws FileNotFoundException{
// TODO implement this
}
/**
* This method builds the Huffman tree from the input file.
*
* @param file the file to use to construct the Huffman tree
* @throws FileNotFoundException
*/
private void buildFromFile(File file) throws
FileNotFoundException {
// read file and build the map of the character frequencies
Map<String, Integer> freqMap = new BSTMap<String,
Integer>();
Scanner scanner = new Scanner(file);
scanner.useDelimiter("");
String character;
while (scanner.hasNext()){
character = scanner.next();
Integer count = freqMap.get(character);
if (count == null){
count = Integer.valueOf(0);
}
freqMap.put(character, count+1);
}
// for each key, make a tree and load it into the priority queue
PriorityQueue<BinaryTree<CountPair>> treeQueue = new
PriorityQueue<BinaryTree<CountPair>>(freqMap.keySet().size(
), new CountPairTreeComparator
BinaryTree<CountPair> tmpTree;
for (String key: freqMap.keySet()){
int frequency = freqMap.get(key);
tmpTree = new BinaryTree<CountPair>(null, new
CountPair(key, frequency), null);
treeQueue.add(tmpTree);
}
// while the size of the priority queue is greater than 1,
combine the top items into a tree and put them back in the
priority queue
BinaryTree<CountPair> tree1, tree2;
int newFrequency;
1/1/13 10:08 PM
Page 2 of
3http://web.cs.mtholyoke.edu/~candrews/cs211/examples/Huffm
anTree.html
String newText;
while (treeQueue.size() > 1){
tree1 = treeQueue.remove();
tree2 = treeQueue.remove();
// If the height of the second tree is less than the height of the
first,
// or the heights are the same and tree2 precedes tree1
alphabetically, swap them so
// the smaller/earlier tree is put on the left
if (tree1.getValue()._text.length() >
tree2.getValue()._text.length()
||( tree1.getValue()._text.length() ==
tree2.getValue()._text.length()
&&
tree1.getValue()._text.compareTo(tree2.getValue()._text) > 0)){
tmpTree = tree1;
tree1 = tree2;
tree2 = tmpTree;
}
// create a new tree combining the two smaller trees,
computing a new frequency that is the sum of the
// children frequencies and a new text that is the appended
combination of the children's text
newFrequency = tree1.getValue()._count +
tree2.getValue()._count;
newText = tree1.getValue()._text + tree2.getValue()._text;
tmpTree = new BinaryTree<CountPair>(tree1, new
CountPair(newText, newFrequency), tree2);
treeQueue.add(tmpTree);
}
// pull the completed tree from the priority queue
BinaryTree<CountPair> tree = treeQueue.remove();
// create map of symbols to code lengths using the tree
Map<String, Integer> codeLengthMap = new Map<String,
Integer>();
// TODO implement this part
buildTreeFromMap(codeLengthMap);
}
/**
* Builds the tree using information found in a compressed file.
*
* The table is the first thing we find in the file. The first piece
of data is the length
* of the table (L). This is followed by L pairs of character and
code length pairs.
*
* @param file the file to read the Huffman code from.
*/
private void buildFromCompressedFile(File file) throws
FileNotFoundException{
// TODO implement this
}
/**
* Read the original file and compress it using the Huffman
codes, writing the result
* into the output file.
*
* @param outputFile the output file
*/
public void saveCompressedFile(File outputFile){
// TODO implement this
}
/**
* Read the compressed file that initialized this object and
write the decoded version out
* into the output file.
*
* @param outputFile the destination file for the uncompressed
file.
*/
public void saveExpandedFile(File outputFile){
// TODO implement this
}
/**
* This method reads in a String of text and returns a String of
0s and 1s corresponding to the Huffman code stored in this tree.
* @param text the text to be encoded
* @return a String representation of the Huffman code
*/
public String encode(String text){
StringBuilder builder = new StringBuilder();
String tmp;
for (int i =0; i < text.length(); i++){
tmp = _lookupTable.get(String.valueOf(text.charAt(i)));
builder.append(tmp);
}
1/1/13 10:08 PM
Page 3 of
3http://web.cs.mtholyoke.edu/~candrews/cs211/examples/Huffm
anTree.html
return builder.toString();
}
/**
* This method reads in a String representation of a Huffman
code corresponding to this Huffman tree and decodes it.
* @param text a String representation of the a Huffman coded
message
* @return the original text
*/
public String decode(String text){
StringBuilder builder = new StringBuilder();
BinaryTree<CountPair> current = _huffmanTree;
for (int i =0; i < text.length(); i++){
char c = text.charAt(i);
if (c == '0'){
current = current.getLeft();
}else if (c == '1'){
current = current.getRight();
}else{
throw new RuntimeException("Encountered unexpected
character in coded String");
}
if (current.isLeaf()){
builder.append(current.getValue()._text);
current = _huffmanTree;
}
}
return builder.toString();
}
private class CountPair{
int _count;
String _text;
private CountPair(String text, int count){
_text = text;
_count = count;
}
}
private class CountPairTreeComparator implements
Comparator<BinaryTree<CountPair>>{
@Override
public int compare(BinaryTree<CountPair> t1,
BinaryTree<CountPair> t2) {
CountPair p1 = t1.getValue();
CountPair p2 = t2.getValue();
if (p1._count != p2._count){
return p2._count - p1._count;
}else if (p1._text.length() != p2._text.length()){
return -p1._text.length() - p2._text.length();
} else{
return p1._text.compareTo(p2._text);
}
}
}
}
1/1/13 9:26 PMCS 211 Homework Five — Fall 2012
Page 1 of
4http://web.cs.mtholyoke.edu/~candrews/cs211/homework/hw5.
html
CS 212 — Homework Five
Can't see the forest...
Due: 30 October 2012, 11:59p
Worth: 75 points
Part One: Implement a Binary Tree
Worth: 15 points
The first step is to build a simple BinaryTree ADT (so it should
support generics). Our needs for the tree
are pretty simple, so you will only need to implement the
following interface:
BinaryTree(BinaryTree<E> left, E value, BinaryTree<E> right)
BinaryTree<E> getLeftChild()
BinaryTree<E> getRightChild()
void setLeftChild(BinaryTree<E>)
void setRightChild(BinaryTree<E>)
void setValue(E)
E getValue()
boolean isLeaf()
For this tree, you will be implementing it in "linked-list" style,
as described in class. For the second part of
the assignment you will be doing a lot of merging of the binary
trees and that would be something of a
pain that outweighs the trouble of the extra null references.
I, of course, expect to see JUnit tests included with this class.
Part Two: Parsing Expressions
Worth: 60 points
One use of trees is to build expression trees. For this
assignment, you will be building an arithmetic
expression tree that can represent arithmetic expressions. The
idea behind expression trees is that inner
nodes are operators (in our case, +,-,*,/), and the leaves are
operands (either constant values or
variables). The value of an expression tree is either the value
stored in the node (if the node has no
children) or the result of applying the operator stored in the
node to its left and right subtrees. So, for
example, the expression x + 5 - 6 would be represented as:
Your task will be to read in an expression, parse it into a tree,
and then let the user perform some basic
operations on the expression. You will create a class called
ArithmeticExpression with the following
1/1/13 9:26 PMCS 211 Homework Five — Fall 2012
Page 2 of
4http://web.cs.mtholyoke.edu/~candrews/cs211/homework/hw5.
html
interface:
ArithmeticExpression(String expression) [25 pts]
This is the constructor. It will take a String containing the
expression. The expression will contain operators (+,-
,*,/), integer constants, and arbitrary strings that should be
interpreted as variables.There is no guarantee that this
expression is valid. If the expression is not valid, this should
throw a ParseException (be sure to indicate where you
had a problem with the parse). To make your lives a little
easier, the expression will be space delimitated. Being the
constructor, this function should only perform the parse a build
the resulting data structure (using a BinaryTree, of
course).
String toString() [10 pts]
This method should return a String containing the parsed
expression. In this case, that means fully parenthesized
according to operator precedence (i.e., * and / have higher
precedence than + and -). For example, "6 + 5 * 2"
should result in "(6+(5*2))". The result should contain no
spaces. Hint: this should sound like some kind of traversal
— what kind?
void setVariable(String name, int value) [10 pts]
This allows the user to set a value for a variable in the
expression. If the variable does not exist in the function,
throw a NotBoundException.
int evaluate() [15 pts]
Obviously, this should return the integer result of evaluating the
expression. Unset variables should be considered to
have the value of 0.
Example usage
Code:
ArithmeticExpression expression = new
ArithmeticExpression("x + 5 * 6");
System.out.println(expression);
expression.setVariable("x", 5);
System.out.println(expression.evaluate());
expression.setVariable("x", 10);
System.out.println(expression.evaluate());
Output:
(x+(5*6))
35
40
Implementation details
The hardest part of this is implementing the parser that builds
the expression tree so that the correct
operator precedence is maintained. For example, given the
expression x + y * 2, assuming that we
interpret the left and right sides of the operators as left and
right children, there are two trees we could
build, but only one of them is correct.
1/1/13 9:26 PMCS 211 Homework Five — Fall 2012
Page 3 of
4http://web.cs.mtholyoke.edu/~candrews/cs211/homework/hw5.
html
So, we can't just start chaining nodes together. Instead, we are
going to use a pair of Stacks to help us
out (that's right, you'll need to pull out your Stack class from
the first homework). One stack will be the
operator stack, and it will hold operators that we don't know
how to use yet. The other stack will be a
tree stack, and will hold the partial binary trees that we have
not fit together yet. As we read tokens from
the input expression, the operation will then be:
If the token is an operand,
make it into a tree and push it on the tree stack
If the token is an operator, operator stack is empty OR the
operator is either * or /,
push the operator on the operator stack
Otherwise:
While the operator stack is not empty
Pop an operator from the operator stack
Pop the top two trees from the tree stack
Create a new tree with the two trees and the operator
Push the new tree on the tree stack
Push the new operator onto the operator stack
When the String is consumed, repeat the above loop to clear out
any unused operators
At the end, the expression tree should be sitting alone in the
tree stack. Clearly, if any of the pops fail, or
if there are more trees in the tree stack at the end of the process,
the expression was invalid.
Another issue you will have is storing the variable values. The
obvious answer would be to replace any
variables in the tree with the value when they get set. Of course,
then you won't be able to change the
variable's value and re-evaluate the expression (which would
rather remove the value of having variables
there). So, we want to build a lookup table to hold the current
values of all of the variables. Very soon,
we will start talking about a data structure tailor-made for this
purpose, but for right now we will just use
an ArrayList. You will need to create some kind of inner class
to hold name/value pairs. Stick these in the
ArrayList and just iterate through everything to find the right
entry. This isn't terribly efficient, but we
are unlikely to have very many variables. Very soon, we will
start talking about a data structure that is
tailor-made to this, but for right now we will put up with this
little bit of inefficiency.
Bonus round
I decided that I would give you the opportunity to earn a little
extra credit on this one. If you chose to do
any of these, be very clear that you did it in your comments, and
provide appropriate test cases
demonstrating them in action.
(4 points) Adjust your code so that it can handle input strings
without spaces.
(4 points) Handle implicit multiplication on variables (i.e., 2x +
5).
(5 points) Rewrite the parser so that it can handle parentheses in
the input string. You will have to
think a little bit about how to handle the logic of this case since
the parentheses affect the
precedence of operations (i.e., they will not be represented in
the tree, they will affect the
structure of the tree).
(5 points) Allow for unary operators. A unary operator would be
an operator that takes only a single
operand (i.e., -5 or +34). Again, you will have to think about
how to change the logic of the parse
to allow these
(5 points) Write a new method called toPostfixString() that will
return the expression in postfix
form.
Turning the assignment in...
Commented source files and tests should be put into a single
directory, zipped, tarred or jarred, and
submitted online into your course dropbox on ella (I only want
source files, I do not want any class files).
Please name your files cs211_pid_hw5.suffix, where pid is your
Mount Holyoke email account name and
suffix is the appropriate suffix for your archive format.
Last modified: Tue Oct 23 18:03:05 EDT 2012
1/1/13 9:26 PMCS 211 Homework Five — Fall 2012
Page 4 of
4http://web.cs.mtholyoke.edu/~candrews/cs211/homework/hw5.
html
1/1/13 9:26 PM
Page 1 of
5http://web.cs.mtholyoke.edu/~candrews/cs211/examples/RBMa
p.html
import java.util.Set;
import java.util.TreeSet;
/**
* This is a skeleton of a red black tree. The basic functionality
of a map backed by a binary search tree is provided, but
* the red black handling has been left as an exercise.
*
* @author C. Andrews
*
* @param <K> the key type of the Map
* @param <V> the value type associated with the key
*/
public class RBMap<K extends Comparable<K>, V>
implements Map<K, V> {
private static enum NodeColor {RED, BLACK};
BinaryTree<Pair> _root =null;
Set<K> _keys;
public RBMap(){
_keys = new TreeSet<K>();
}
/**
* Add an element to the map.
*
* If the key is already present in the map, the value is replaced
with {@code value}.
*
* @param key the key to associate the value with
* @param value the value being added to the map
*/
@Override
public void put(K key, V value) {
BinaryTree<Pair> tmp = new BinaryTree<Pair>(null, new
Pair(key, value), null);
BinaryTree<Pair> current = _root;
BinaryTree<Pair> parent = null;
_keys.add(key);
while (current != null){
parent = current;
if (key.compareTo(current.getValue()._key) == 0){ // they are
the same, just update the value
current.getValue()._value = value;
return;
}else if (key.compareTo(current.getValue()._key) < 0){ // the
key is smaller, go left
current = current.getLeft();
}else{ // the key is larger, go right
current = current.getRight();
}
}
tmp.setParent(parent);
if (parent == null){
_root = tmp;
}else{
if (key.compareTo(parent.getValue()._key) < 0){
parent.setLeft(tmp);
}else{
parent.setRight(tmp);
}
}
// TODO rebalance the tree
}
/**
* Perform a lookup in the map based on the input key.
1/1/13 9:26 PM
Page 2 of
5http://web.cs.mtholyoke.edu/~candrews/cs211/examples/RBMa
p.html
*
* @param key the key associated with the value to be returned
*/
@Override
public V get(K key) {
BinaryTree<Pair> tmp = find(key);
if(tmp == null)
return null;
else
return tmp.getValue()._value;
}
/**
* This private method finds nodes in the tree based on the key
value.
*
* If the key exists in the map, this returns the node associated
with it (not just the value). If the
* key is not present, this returns null. This is used to
implement get and remove.
*
* @param key the key that we are looking for
* @return the node containing the key or null if the key is not
present
*/
private BinaryTree<Pair> find(K key){
BinaryTree<Pair> current = _root;
while (current != null &&
key.compareTo(current.getValue()._key) != 0){
if (key.compareTo(current.getValue()._key) < 0){
current = current.getLeft();
}else{
current = current.getRight();
}
}
if (current != null)
return current;
else
return null;
}
/**
* Does the map contain the given key?
*
* @param key the key value to look for in the map
* @return a boolean value indicating if the key is present
*/
@Override
public boolean containsKey(K key) {
return get(key) != null;
}
/**
* Remove the value associated with {@code key} from the
map.
*
* Removes the key and value pair and returns the value.
*
* @param key the key for the value we are trying to remove
* @return the value associated with the key or null if the key
is not present in the map
*/
@Override
public V remove(K key) {
_keys.remove(key);
BinaryTree<Pair> toRemove = find(key);
BinaryTree<Pair> child;
V value;
if (toRemove == null){
return null;
}
value = toRemove.getValue()._value;
if (toRemove.getLeft() != null && toRemove.getRight() !=
null){
BinaryTree<Pair>tmp = toRemove;
NodeColor color = toRemove.getValue()._color;
1/1/13 9:26 PM
Page 3 of
5http://web.cs.mtholyoke.edu/~candrews/cs211/examples/RBMa
p.html
toRemove = successor(toRemove);
tmp.setValue( toRemove.getValue());
tmp.getValue()._color = color;
}
if (toRemove.getLeft() != null){
child = toRemove.getLeft();
}else{
child = toRemove.getRight();
}
if (child != null){
child.setParent(toRemove.getParent());
}
if (toRemove.getParent() == null){
_root = child;
}else if (toRemove.getParent().getLeft() == toRemove){
toRemove.getParent().setLeft(child);
}else{
toRemove.getParent().setRight(child);
}
// TODO rebalance tree if necessary
return value;
}
/**
* Return the set of all keys present in the map.
*
* @return the {@code Set} of all keys in the map
*/
@Override
public Set<K> keySet() {
return _keys;
}
/**
* A private helper that finds the immediate successor of a node
in the tree.
*
* @param t the node we are trying to find the successor of
* @return the immediate successor of the node or null if there
isn't one
*/
private BinaryTree<Pair> successor(BinaryTree<Pair> t){
if (t.getRight() != null){
return minimum(t.getRight());
}
BinaryTree<Pair> parent = t.getParent();
while (parent != null && parent.getRight() == t){
t = parent;
parent = parent.getParent();
}
return parent;
}
/**
* A private helper that finds the minimum value in the tree
rooted at t.
*
* This will fail if t is null since that would be an invalid
operation.
*
* @param t the subtree we are exploring
* @return the minimum value in t
*/
private BinaryTree<Pair> minimum(BinaryTree<Pair> t){
while (t.getLeft() != null){
t = t.getLeft();
}
return t;
}
1/1/13 9:26 PM
Page 4 of
5http://web.cs.mtholyoke.edu/~candrews/cs211/examples/RBMa
p.html
/**
* A private helper that finds the maximum value in the tree
rooted at t.
*
* This will fail if t is null since that would be an invalid
operation.
*
* @param t the subtree we are exploring
* @return the maximum value in t
*/
@SuppressWarnings("unused")
private BinaryTree<Pair> maximum(BinaryTree<Pair> t){
while (t.getRight() != null){
t = t.getRight();
}
return t;
}
/**
* Returns a String representation of the tree.
*
* The representation is a preorder traversal of the tree in
which each node is printed out in the
* form of the key, followed by a colon and then a B or an R,
all in square brackets. So a tree
* with root 5 and children 3 and 9 would look like
[5:B][3:R][9:R].
*
*/
public String toString(){
// TODO implement this method
}
/**
* Returns the black height of the tree.
*
* If there are any violations, this returns -1.
*
* @return the black height or -1 if there are any violations
*/
public int blackHeight(){
// TODO implement this method
}
/**
* Indicates if there is a red violation in the tree
*
* @return a boolean value that indicates if there is a red
violation in the tree
*/
public boolean redViolation(){
// TODO implement this method
}
/**
* This is a simple wrapper class that provides the associations
in the tree.
*
* @author C. Andrews
*
*/
private class Pair{
private K _key;
private V _value;
private NodeColor _color;
private Pair(K key, V value){
_key = key;
_value =value;
_color = NodeColor.RED; // all new nodes are RED
}
1/1/13 9:26 PM
Page 5 of
5http://web.cs.mtholyoke.edu/~candrews/cs211/examples/RBMa
p.html
}
}

More Related Content

PDF
Please read the comment ins codeExpressionTree.java-------------.pdf
shanki7
 
DOCX
----------Evaluator-java---------------- package evaluator- import j.docx
janettjz6sfehrle
 
PDF
java write a program to evaluate the postfix expressionthe program.pdf
arjuntelecom26
 
DOCX
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
curwenmichaela
 
PDF
The concept of stack is extremely important in computer science and .pdf
arihantsherwani
 
DOCX
----------Evaluator-java---------------- package evaluator- import j.docx
Adamq0DJonese
 
PPTX
lecture-8-expression-trees.pptx 886565435
iswas2524
 
DOCX
java assignment
Jack Eastwood
 
Please read the comment ins codeExpressionTree.java-------------.pdf
shanki7
 
----------Evaluator-java---------------- package evaluator- import j.docx
janettjz6sfehrle
 
java write a program to evaluate the postfix expressionthe program.pdf
arjuntelecom26
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
curwenmichaela
 
The concept of stack is extremely important in computer science and .pdf
arihantsherwani
 
----------Evaluator-java---------------- package evaluator- import j.docx
Adamq0DJonese
 
lecture-8-expression-trees.pptx 886565435
iswas2524
 
java assignment
Jack Eastwood
 

Similar to META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx (20)

DOCX
Posfix
Fajar Baskoro
 
PPTX
MATHEMATICAL EXPRESSION EVALUATION USING TREES.pptx
abhishekamar5
 
PDF
Tested on Eclipse and both class should be in same packageimport.pdf
anuradhasilks
 
PPT
Lec19
Nikhil Chilwant
 
PDF
Data structuresUsing java language and develop a prot.pdf
armyshoes
 
PPTX
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
RashidFaridChishti
 
PPTX
Operators
VijayaLakshmi506
 
PPT
Operators
Daman Toor
 
PDF
Applications of stack
A. S. M. Shafi
 
PDF
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
arjuncorner565
 
PDF
Create an implementation of a binary tree using the recursive appr.pdf
federaleyecare
 
PPT
object oriented programming java lectures
MSohaib24
 
PPTX
Lect-3 Java VKA.pptx
VijayaAhire2
 
DOCX
Operators
loidasacueza
 
PPTX
Lecture_04.2.pptx
RockyIslam5
 
PPT
data structure and algorithm by bomboat_3
jateno3396
 
PDF
Need help with this paperThis assignment consists of writing resea.pdf
sktambifortune
 
PPT
1.4 expression tree
Krish_ver2
 
PPTX
conversion of Infix to Postfix conversion using stack
yashodamb
 
PPTX
Programming Homework Help
Programming Homework Help
 
MATHEMATICAL EXPRESSION EVALUATION USING TREES.pptx
abhishekamar5
 
Tested on Eclipse and both class should be in same packageimport.pdf
anuradhasilks
 
Data structuresUsing java language and develop a prot.pdf
armyshoes
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
RashidFaridChishti
 
Operators
VijayaLakshmi506
 
Operators
Daman Toor
 
Applications of stack
A. S. M. Shafi
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
arjuncorner565
 
Create an implementation of a binary tree using the recursive appr.pdf
federaleyecare
 
object oriented programming java lectures
MSohaib24
 
Lect-3 Java VKA.pptx
VijayaAhire2
 
Operators
loidasacueza
 
Lecture_04.2.pptx
RockyIslam5
 
data structure and algorithm by bomboat_3
jateno3396
 
Need help with this paperThis assignment consists of writing resea.pdf
sktambifortune
 
1.4 expression tree
Krish_ver2
 
conversion of Infix to Postfix conversion using stack
yashodamb
 
Programming Homework Help
Programming Homework Help
 

More from andreecapon (20)

DOCX
MGMT 511Location ProblemGeorge Heller was so successful in.docx
andreecapon
 
DOCX
MGMT 464From Snowboarders to Lawnmowers Case Study Case An.docx
andreecapon
 
DOCX
MG345_Lead from Middle.pptLeading from the Middle Exe.docx
andreecapon
 
DOCX
MGMT 345Phase 2 IPBusiness MemoToWarehouse ManagerFrom[You.docx
andreecapon
 
DOCX
MGMT 3720 – Organizational BehaviorEXAM 3(CH. 9, 10, 11, & 12).docx
andreecapon
 
DOCX
Mexico, Page 1 Running Head MEXICO’S CULTURAL, ECONOMI.docx
andreecapon
 
DOCX
MGM316-1401B-01Quesadra D. GoodrumClass Discussion Phase2.docx
andreecapon
 
DOCX
METROPOLITAN PLANNING ANDENVIRONMENTAL ISSUESn May 2008, the N.docx
andreecapon
 
DOCX
Methods of Moral Decision Making REL 330 Christian Moralit.docx
andreecapon
 
DOCX
MEPS_Inpatient Stay database.csduidpiddupersidevntidxeventrnerhevi.docx
andreecapon
 
DOCX
METHODS TO STOP DIFFERENT CYBER CRIMES .docx
andreecapon
 
DOCX
Mexico The Third War Security Weekly Wednesday, February 18.docx
andreecapon
 
DOCX
Mercy College .docx
andreecapon
 
DOCX
Merger AnalysisMerger Analysis Case Study© 2007 South UniversityFr.docx
andreecapon
 
DOCX
MGMT 301 EOY Group” Case Study and Power Point Presentation G.docx
andreecapon
 
DOCX
MGMT 464New Manager’s Case Study Case Analysis Worksheet #.docx
andreecapon
 
DOCX
Menu Management Options· · APRN504 - 5886 - HEALTH POLICY .docx
andreecapon
 
DOCX
MGMT 673 Problem Set 51. For each of the following economic cond.docx
andreecapon
 
DOCX
Mental Illness Stigma and the Fundamental Components ofSuppo.docx
andreecapon
 
DOCX
Merck & Co. Inc. MRKCopy and pasteany three Notes to the Fina.docx
andreecapon
 
MGMT 511Location ProblemGeorge Heller was so successful in.docx
andreecapon
 
MGMT 464From Snowboarders to Lawnmowers Case Study Case An.docx
andreecapon
 
MG345_Lead from Middle.pptLeading from the Middle Exe.docx
andreecapon
 
MGMT 345Phase 2 IPBusiness MemoToWarehouse ManagerFrom[You.docx
andreecapon
 
MGMT 3720 – Organizational BehaviorEXAM 3(CH. 9, 10, 11, & 12).docx
andreecapon
 
Mexico, Page 1 Running Head MEXICO’S CULTURAL, ECONOMI.docx
andreecapon
 
MGM316-1401B-01Quesadra D. GoodrumClass Discussion Phase2.docx
andreecapon
 
METROPOLITAN PLANNING ANDENVIRONMENTAL ISSUESn May 2008, the N.docx
andreecapon
 
Methods of Moral Decision Making REL 330 Christian Moralit.docx
andreecapon
 
MEPS_Inpatient Stay database.csduidpiddupersidevntidxeventrnerhevi.docx
andreecapon
 
METHODS TO STOP DIFFERENT CYBER CRIMES .docx
andreecapon
 
Mexico The Third War Security Weekly Wednesday, February 18.docx
andreecapon
 
Mercy College .docx
andreecapon
 
Merger AnalysisMerger Analysis Case Study© 2007 South UniversityFr.docx
andreecapon
 
MGMT 301 EOY Group” Case Study and Power Point Presentation G.docx
andreecapon
 
MGMT 464New Manager’s Case Study Case Analysis Worksheet #.docx
andreecapon
 
Menu Management Options· · APRN504 - 5886 - HEALTH POLICY .docx
andreecapon
 
MGMT 673 Problem Set 51. For each of the following economic cond.docx
andreecapon
 
Mental Illness Stigma and the Fundamental Components ofSuppo.docx
andreecapon
 
Merck & Co. Inc. MRKCopy and pasteany three Notes to the Fina.docx
andreecapon
 

Recently uploaded (20)

PPTX
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
DOCX
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
PPTX
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
DOCX
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
PPTX
Artificial Intelligence in Gastroentrology: Advancements and Future Presprec...
AyanHossain
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
PDF
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
DOCX
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPTX
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PPTX
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
PDF
Module 2: Public Health History [Tutorial Slides]
JonathanHallett4
 
PPTX
How to Apply for a Job From Odoo 18 Website
Celine George
 
PPTX
Care of patients with elImination deviation.pptx
AneetaSharma15
 
PPTX
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
PPTX
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
Artificial Intelligence in Gastroentrology: Advancements and Future Presprec...
AyanHossain
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
Module 2: Public Health History [Tutorial Slides]
JonathanHallett4
 
How to Apply for a Job From Odoo 18 Website
Celine George
 
Care of patients with elImination deviation.pptx
AneetaSharma15
 
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
Artificial-Intelligence-in-Drug-Discovery by R D Jawarkar.pptx
Rahul Jawarkar
 

META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx

  • 1. META-INF/MANIFEST.MF Manifest-Version: 1.0 .classpath PriorityQueue.classpublicsynchronizedclass PriorityQueue { Heap q; public void PriorityQueue(int, java.util.Comparator); public Object peek(); public Object remove(); void add(Object); boolean isEmpty(); public int size(); } PriorityQueue.javaPriorityQueue.javaimport java.util.Comparat or; publicclassPriorityQueue<E>{ Heap q; /** *PriorityQueue initializes the queue. * * @param initialCapacity an int that is the heaps initial size.
  • 2. * @param comparator the priority of various imputs. */ publicPriorityQueue(int initialCapacity,Comparator<?super E> comparator){ q=newHeap(initialCapacity,comparator); } /** * Peek, returns the next item in the queue without removing it. * * If it is empty then null is returned. * @return the next item in the queue. */ public E peek(){ if(q.size()==0){ returnnull; } return(E) q.findMax(); } /** * This removes the first item from the queue. * * It returns null if the queue is empty. * @return the first item in the queue. */ public E remove(){ if(q.size()==0){ returnnull; } return(E) q.removeMax(); } /**
  • 3. * This adds item to the queue * @param item that is added to the queue. */ void add(E item){ q.insert(item); } /** * isEmpty returns if the queue is empty or not. * * @return boolean if the queue is empty or not. */ boolean isEmpty(){ if(q.size()!=0){ returnfalse; } returntrue; } /** * size returns the size of the queue. * * @return int the size of the queue. */ publicint size(){ return q.size(); } } ArithmeticExpression.classpublicsynchronizedclass ArithmeticExpression { BinaryTree t; java.util.ArrayList list; String equation; void ArithmeticExpression(String) throws java.text.ParseException;
  • 4. public String toString(BinaryTree); public String toPostfixString(BinaryTree); void setVariable(String, int) throws java.rmi.NotBoundException; public int evaluate(BinaryTree); } ArithmeticExpression.javaArithmeticExpression.javaimport java .rmi.NotBoundException; import java.text.ParseException; import java.util.ArrayList; import java.util.Stack; /** * ArithmeticExpression takes equations in the form of strings c reates a binary * tree, and can return either the regular or postfix equation. It a lso allows * them to be calculated. * * * Extra Credit: * ** it can handle spaces or no spaces in the string inputted. ** it can return * regular or postfix notation * * @author tai-lanhirabayashi * */ publicclassArithmeticExpression{ BinaryTree t; ArrayList list; String equation;
  • 5. /** * ArithmeticExpression is the construction which takes in a space * delimitated equation containing "*,/,+,- " symbols and converts it into a * binary tree. * * If the expression is not valid it will throw a ParseExceptio n. This is * the constructor. It will take a String containing the express ion. * * ** The equation can take in stings delimitated by spaces, o r withot any * spaces. If it contains a mix, then the non spaced part(s) wil l be * considered to be a variable. * * @param expression * @throws ParseException * if the string is not a valid equation */ @SuppressWarnings({"unchecked","rawtypes"}) ArithmeticExpression(String expression)throwsParseException{ //hold the string globally equation = expression; //create a new arrayList to be used globally that holds the variab les list =newArrayList(); //split the string String[] s = expression.split(" "); // create a stack of tree's and operators
  • 6. Stack tree =newStack(); Stack operator =newStack(); //create the string Next String next =""; // if the string expression doesnt contain spaces if(!expression.contains(" ")){ int i =0; //if it starts with an operator throw an error this cannot be. if(expression.charAt(0)=='+'|| expression.charAt(0)=='*' || expression.charAt(0)=='-' || expression.charAt(0)=='/'){ System.out.println("this equation starts with a operator."); thrownewParseException(expression,0); } // if the expression ends with an operator throw an error this can not be. if(expression.charAt(expression.length()-1)=='+' || expression.charAt(expression.length()-1)=='*' || expression.charAt(expression.length()-1)=='-' || expression.charAt(expression.length()-1)=='/'){ System.out.println("this equation ends with a operator."); thrownewParseException(expression, expression.length()); } //go through each characer in the expression and see if its a num ber/variable, or operator. while(i < expression.length()){ if(expression.charAt(i)=='+'|| expression.charAt(i)=='*' || expression.charAt(i)=='-' || expression.charAt(i)=='/'){ // if the character is a operator add a space to the begining and f
  • 7. ront and add it to the "next" string String str =String.valueOf(expression.charAt(i)); next = next +" "+ str +" "; }else{ // if its an operator add it to the end of the "next" string. next = next + expression.charAt(i); } // increase i to move to the next character. i++; } // split the new string with added spaces. s = next.split(" "); } // if the string still doesnt exist throw the error. if(s.length ==0){ System.out .println("there has been an error. You have not entered a string with any characters"); thrownewParseException(expression,0); } // make sure there arent two operators in a row. for(int i =0; i < s.length; i++){ if(i >=1 &&(s[i].equals("+")|| s[i].equals("-") || s[i].equals("*")|| s[i].equals("/"))){ if(s[i -1].equals("+")|| s[i -1].equals("-") || s[i -1].equals("*")|| s[i -1].equals("/")){ System.out .println("there were two operators in a row. The equation is not valid."); thrownewParseException(expression, i);
  • 8. } } // check to make sure there arent two operands in a row in the St ring[] if(i >=1 &&(s[i].equals("+")==false&& s[i].equals("-")==false && s[i].equals("*")==false&& s[i].equals("/")==false)){ if(s[i -1].equals("+")==false && s[i -1].equals("-")==false && s[i -1].equals("*")==false && s[i -1].equals("/")==false){ System.out .println("there were two operands in a row. The equation is not valid."); thrownewParseException(expression, i); } } // if its a number create a new tree node, and add it to the tree st ack if(s[i].equals("+")==false&& s[i].equals("-")==false && s[i].equals("*")==false&& s[i].equals("/")==false){ BinaryTree o =newBinaryTree(null, s[i],null); tree.add(o); }elseif(operator.empty()|| s[i].equals("*")|| s[i].equals("/")){ //if its a * or / symbol hold it to ensure order of operation operator.push(s[i]); }else{ //group the tree's together. while(operator.empty()==false){ String operatorHeld =(String) operator.pop();
  • 9. BinaryTree one =(BinaryTree) tree.pop(); BinaryTree two =(BinaryTree) tree.pop(); BinaryTree n =newBinaryTree(one, operatorHeld, two); tree.push(n); } operator.push(s[i]); } } // at the end ensure that the operator is empty. while(operator.empty()==false){ String operatorHeld =(String) operator.pop(); BinaryTree one =(BinaryTree) tree.pop(); BinaryTree two =(BinaryTree) tree.pop(); BinaryTree n =newBinaryTree(one, operatorHeld, two); tree.push(n); } //if there is more than 1 tree at the end something went wrong // this should not occur as it should have been caught earlier // this is just to ensure completeness. if(tree.size()>=2){ System.out .println("this expression is invalid. There were more operands t han operators."); System.out .println("this should not occur it should have been caught earlie r"); while(tree.empty()==false){ return; } } //if there are still operators there is something wrong // this should not occur as it should have been caught earlier // this is just to ensure completeness.
  • 10. if(operator.empty()==false){ System.out .println("this should not occur it should have been caught earlie r."); System.out .println("there were too many operators in the string the progra m cannot continue."); { return; } } // set the tree globally t =(BinaryTree) tree.pop(); } /** * toString returns the String equation of that the passed in bi nary tree * represents. * * @param tree * that represents an equation * @return the String that is represented by the passed in Bin aryTree. */ @SuppressWarnings("rawtypes") publicString toString(BinaryTree tree){ // if its a leaf return its value if(tree.isLeaf()==true){ return(String) tree.getValue(); }else{ //else combine each parent child combination
  • 11. //call recursively, and contain each call in parenthesis. String s =("("+ toString(tree.getLeftChild())+ tree.getValue() + toString(tree.getRightChild())+")"); return s; } } /** * toPostfixString returns the string containing the parsed exp ression in * postFix notation with spaces between numbers and operato rs to ensure clarity. * * @param tree that represents an equation * @return the String that is represented by the passed in Bin aryTree in * postfix form. */ @SuppressWarnings("unchecked") publicString toPostfixString(BinaryTree tree){ //if its a leaf return its value if(tree.isLeaf()==true){ return(String) tree.getValue(); }else{ //otherwise call recursively down the tree // and add the operator to the end of the two operands. // also add spaces to allow numbers to be seen individually. String s = toPostfixString(tree.getRightChild())+" " + toPostfixString(tree.getLeftChild())+" " + tree.getValue(); System.out.println("this is what s is "+ s); return s; }
  • 12. } /** * This allows the user to set a value for a variable in the exp ression. If * the variable does not exist in the function, throw a NotBou ndException. * * @param name of the variable * @param value that the variable has * @throws NotBoundException if the variable is not used in the equation */ void setVariable(String name,int value)throwsNotBoundExcepti on{ //Note var, is not a Var it is a seperate class that is an object. //if the equation string doesnt contain the variable throw an erro r if(!equation.contains(name)){ thrownewNotBoundException(); } // else continue and check if the var object is already in the list for(int i =0; i < list.size(); i++){ var v =(var) list.get(i); if(v.getName().equals(name)){ //if so change the value of the var object v.setValue(value); return; } } // otherwise add the var object to the list.
  • 13. list.add(new var(name, value)); } /** * Evaluate returns the integer result of the expression. * * Variables that are not declared are calculated at 0. * * @return the value of the equation */ @SuppressWarnings("unused") publicint evaluate(BinaryTree tree){ //if it is a leaf if(tree.isLeaf()==true){ String s =(String) tree.getValue(); //if all characters are numbers simply skip down to return the in teger value. for(int i =0; i < s.length(); i++){ if(s.charAt(i)=='0'|| s.charAt(i)==('1') || s.charAt(i)=='2'|| s.charAt(i)=='3' || s.charAt(i)=='4'|| s.charAt(i)=='5' || s.charAt(i)=='6'|| s.charAt(i)=='7' || s.charAt(i)=='8'|| s.charAt(i)=='9'){ }else{ //if there are non numeric characters check if the list has their v alues for(int j =0; j < list.size(); j++){ var h =(var) list.get(j); if(h.getName().equals(s)){ return h.getValue(); }
  • 14. } //otherwise tell the user that this variable cannot be found and t hat its value is calulated at 0 System.out.println("this variable "+ s +" cannot be found! Its value will be 0."); return0; } returnInteger.parseInt((String) tree.getValue()); } } //find the left and right values of the tree int left = evaluate(tree.getLeftChild()); int right = evaluate(tree.getRightChild()); //calculate appropriately. if(tree.getValue().equals("*")){ return left * right; }elseif(tree.getValue().equals("/")){ return left / right; }elseif(tree.getValue().equals("+")){ return left + right; } return left - right; } } Map.classpublicsynchronizedclass Map { BSTMap root;
  • 15. BSTMap found; java.util.TreeSet set; public void Map(); public void put(Comparable, Object); public Object get(Comparable); public boolean containsKey(Comparable); private BSTMap getBSTMap(Comparable); public Object remove(Comparable); private BSTMap sucessor(BSTMap); public java.util.Set keySet(); } Map.javaMap.javaimport java.util.Set; import java.util.TreeSet; publicclassMap<K extendsComparable<K>,V>{ BSTMap root; BSTMap found; TreeSet<K> set; /** * Map initializes the map. */ publicMap(){ set=newTreeSet<K>(); root=null; found=null; } /** * put loads the Key and value into a BSTMap object, and the key into the set.
  • 16. * * If the key already exists the value is changed to the new va lue. * @param key the K key value * @param value the V value value */ publicvoid put(K key, V value){ //if the root is null this is the root if(root==null){ root=newBSTMap(key,value); set.add(key); //if the key exists then change the value }elseif(get(key)!=null){ getBSTMap(key).obj.value=value; }else{ //otherwise create a new BSTMap BSTMap i =newBSTMap(key,value); //add it to the set set.add(key); //and find its place in the BSTmap tree.No key can be identical. boolean done=false; BSTMap c= root; while(done==false){ //if it is bigger go right if(key.compareTo((K) c.obj.getKey())>=0){ if(c.getRight()==null){ c.setRight(i); done=true; }else{ c=c.getRight();
  • 17. } //if it is smaller go left. }elseif(key.compareTo((K) c.obj.getKey())<0){ if(c.getLeft()==null){ c.setLeft(i); done=true; }else{ c=c.getLeft(); } } } } } /** * This finds the value associated with they key. If this key c annot be found null is returned. * @param key the K key value * @return V the associated V value. */ public V get(K key){ BSTMap current= root; if(root==null){ returnnull; } while(current!=null&& current.obj.getKey().equals(key)==false ){ if(key.compareTo((K) current.obj.getKey())<0){ current=current.getLeft(); }else{ current=current.getRight(); }
  • 18. } if(current==null){ returnnull; } if(current.obj.getKey().equals(key)){ return(V) current.obj.getValue(); } returnnull; } /** *containsKey returns boolean if the key exists in the map. * @param key the K key value to look for * @return boolean if it exists */ publicboolean containsKey(K key){ BSTMap current= root; if(root==null){ returnfalse; } while(current!=null&& current.obj.getKey().equals(key)==false ){ if(key.compareTo((K) current.obj.getKey())<0){ current=current.getLeft(); }else{ current=current.getRight(); } } if(current==null){ returnfalse; } return current.obj.getKey().equals(key); } /** * getBSTMap returns the BSTMap associated with a key val
  • 19. ue * @param key the K key value * @return BSTMap contained the K key. */ privateBSTMap getBSTMap(K key){ BSTMap current= root; if(root==null){ returnnull; } while(current!=null&& current.obj.getKey().equals(key)==false ){ if(key.compareTo((K) current.obj.getKey())<0){ current=current.getLeft(); }else{ current=current.getRight(); } } if(current.obj.getKey().equals(key)){ return current; } returnnull; } /** * remove removes the BSTMap associated with they key, an d returns its associated value. * * If the key cannot be found null is returned * @param key the K key value to be found * @return V the value of associated with the BSTMap contai ning the K key value. */ public V remove(K key){ if(root==null){ returnnull; }elseif(root.obj.getKey().equals(key)){
  • 20. System.out.println("the node to remove is the root."); V val=(V) root.obj.getValue(); if(root.isLeaf()){ root=null; }elseif(root.getLeft()==null){ root=root.getRight(); }elseif(root.getRight()==null){ root=root.getLeft(); }else{ root=sucessor(root); } return val; } BSTMap n= getBSTMap(key); if(n==null){ returnnull; }else{ set.remove(key); V a=(V) n.obj.getValue(); BSTMap temp=null; BSTMap child=null; if(n.isLeaf()){ temp=n; n=null; }elseif(n.getLeft()!=null&& n.getLeft().getRight()==null){ temp=n; n.getLeft().setRight(n.right); n.setLeft(null); }elseif(n.getRight()!=null&& n.getRight().getLeft()==null){ temp=n; n.getRight().setLeft(n.getLeft()); n.setRight(null); }else{ temp=sucessor(n); n.setRight(null);
  • 21. } System.out.println("this is the temp:"+ temp.obj.key); if(temp.getLeft()!=null){ child=temp.getLeft(); }else{ child=temp.getRight(); }if(child!=null){ child.parent=temp.parent; }if(temp.parent.getLeft()==temp){ temp.parent.setLeft(child); }else{ temp.parent.setRight(child); } return a; } } privateBSTMap sucessor(BSTMap n){ boolean running=true; BSTMap current=n.getRight(); while(running){ if(current.getLeft()!=null){ current=current.getLeft(); }else{ running=false; } } return current; } /** * keySet returns a Set of the K key values in the map. * @return
  • 22. */ publicSet<K> keySet(){ return set; } } BinaryTree.classpublicsynchronizedclass BinaryTree { Object v; BinaryTree treeLeft; BinaryTree treeRight; void BinaryTree(BinaryTree, Object, BinaryTree); BinaryTree getLeftChild(); BinaryTree getRightChild(); void setLeftChild(BinaryTree); void setRightChild(BinaryTree); void setValue(Object); Object getValue(); boolean isLeaf(); } BinaryTree.javaBinaryTree.java /** * BinaryTree is a form of linked nodes that form a tree. * * @author tai-lan hirabayashi * * @param <E> the object value that is within each node. */ publicclassBinaryTree<E>{ E v; BinaryTree<E> treeLeft; BinaryTree<E> treeRight;
  • 23. /** * BinaryTree creates a new node binaryTree which holds an object value. * It takes in the value, left and right child and holds them wi thin the node. * @param left the left child of the node. * @param value the object the node holds * @param right the right child of the node */ BinaryTree(BinaryTree<E> left, E value,BinaryTree<E> right){ v=value; treeLeft=left; treeRight=right; } /** * getLeftChild returns the left child node. * @return the left child, a binary tree node. */ BinaryTree<E> getLeftChild(){ return treeLeft; } /** * getRightChild returns the right child node. * @return the right child,a binaryTree node. */ BinaryTree<E> getRightChild(){ return treeRight; } /** * setLeftChild, sets the left child of the current node. * @param l is the left child, a binaryTree node. */
  • 24. void setLeftChild(BinaryTree<E> l){ treeLeft=l; } /** * setRightChild, sets the right child of the current node. * @param r the right child, a binaryTree node. */ void setRightChild(BinaryTree<E> r){ treeRight=r; } /** * setValue sets the value of a node. * @param object value of the node. */ void setValue(E object){ v=object; } /** * getValue returns the value held in the node. * @return the object value of the node. */ E getValue(){ return v; } /** * isLeaf checks if the node is a leaf node by checking if it ha s children. * @return boolean if the node is a leaf node. */ boolean isLeaf(){ if(getLeftChild()==null&& getRightChild()==null){ returntrue;
  • 25. } returnfalse; } } HuffmanTreeTest.classpublicsynchronizedclass HuffmanTreeTest { HuffmanTree h; String t; public void HuffmanTreeTest(); public void start() throws java.io.FileNotFoundException; public void testEncode(); public void testDecode(); } HuffmanTreeTest.javaHuffmanTreeTest.java importstatic org.junit.Assert.*; import java.io.File; import java.io.FileNotFoundException; import org.junit.Before; import org.junit.Test; publicclassHuffmanTreeTest{ HuffmanTree h; String t; /** * start creates a test case * @throws FileNotFoundException */
  • 26. @Before publicvoid start()throwsFileNotFoundException{ h =HuffmanTree.newTreeFromFile(newFile("/Users/tai- lanhirabayashi/Desktop/test.txt")); } /** * testEncode tries to encode a string. */ @Test publicvoid testEncode(){ t = h.encode("This program must work!"); } /** * testDecode tries to decode the string. */ @Test publicvoid testDecode(){ assertEquals("This program must work!", h.decode(t)); } } HTreeTest.classpublicsynchronizedclass HTreeTest { HTree t; public void HTreeTest(); public void start(); public void testGetBelow(); public void testGetF(); public void testGetS(); public void testGetL();
  • 27. public void testGetR(); public void testIsLeaf(); public void testSetL(); public void testSetR(); } HTreeTest.javaHTreeTest.javaimportstatic org.junit.Assert.*; import org.junit.Before; import org.junit.Test; publicclassHTreeTest{ HTree t; /** * Start initializes a test case of HTree */ @Before publicvoid start(){ t=newHTree(1,"one"); HTree a=newHTree(2,"two"); HTree b=newHTree(3,"three"); t.setL(a); t.setR(b); } /** * testGetBelow tests GetBelow */ @Test publicvoid testGetBelow(){ assertEquals(1,t.getBelow()); assertEquals(0,t.getL().getBelow());
  • 28. HTree a=newHTree(4,"a"); HTree b=newHTree(5,"b"); t.getL().setL(a); t.getL().setR(b); assertEquals(2,t.getBelow()); } /** * testGetF tests getF */ @Test publicvoid testGetF(){ assertEquals(1,t.getF()); assertEquals(2,t.getL().getF()); assertEquals(3,t.getR().getF()); } /** * testGetS tests getS */ @Test publicvoid testGetS(){ assertEquals("one",t.getS()); assertEquals("two",t.getL().getS()); assertEquals("three",t.getR().getS()); } /** * testGetL tests getL */ @Test publicvoid testGetL(){ assertEquals(2,t.getL().getF()); assertEquals(null,t.getL().getL());
  • 29. } /** * testGetR tests getR */ @Test publicvoid testGetR(){ assertEquals(3,t.getR().getF()); assertEquals(null,t.getR().getR()); } /** * testIsLeaf tests isLeaf */ @Test publicvoid testIsLeaf(){ assertEquals(false,t.isLeaf()); assertEquals(true,t.getR().isLeaf()); assertEquals(true,t.getL().isLeaf()); } /** * testSetL tests setL */ @Test publicvoid testSetL(){ assertEquals(2,t.getL().getF()); t.setL(null); assertEquals(null,t.getL()); } /** * testSetR tests setR */ @Test
  • 30. publicvoid testSetR(){ assertEquals(3,t.getR().getF()); t.setR(null); assertEquals(null,t.getR()); } } Heap$MaxHeapComparator.classpublicsynchronizedclass Heap$MaxHeapComparator implements java.util.Comparator { public void Heap$MaxHeapComparator(); public int compare(Comparable, Comparable); } Heap$MinHeapComparator.classpublicsynchronizedclass Heap$MinHeapComparator implements java.util.Comparator { public void Heap$MinHeapComparator(); public int compare(Comparable, Comparable); } Heap.classpublicsynchronizedclass Heap { int s; Object[] h; int maxS; java.util.Comparator c; public void Heap(int, java.util.Comparator); public Object findMax(); public Object removeMax(); public void insert(Object); public int size(); private void siftUp(int); private void siftDown(int); }
  • 31. Heap.javaHeap.javaimport java.lang.reflect.Array; import java.util.Comparator; import java.util.NoSuchElementException; publicclassHeap<E>{ int s; Object[] h; int maxS; Comparator c; /** * Heap takes in the initial size of the heap. * @param i the integer value of the size of the heap. */ publicHeap(int i,Comparator<?super E> comparator){ c=comparator; s=0; maxS=i; h=newObject[i]; } /** * findMax returns the largest item of the heap. * If the heap is empty it will throw a noSuchElementExcepti on. * @return E the max object */ public E findMax(){ if(s==0){ System.out.println("an error has been thrown because the heap i s empty"); thrownewNoSuchElementException();
  • 32. } return(E) h[0]; } /** * removeMax removes the largest item. If the list is empty a NoSuchElementException is thrown. * @return the max object */ public E removeMax(){ if(s==0){ System.out.println("an error has been thrown because the heap i s empty"); thrownewNoSuchElementException(); } E last =(E) h[s-1]; E first =(E) h[0]; h[0]=last; h[s-1]=null; s--; siftDown(0); return first; } /** * insert inserts an item into the heap and bubbles it into the correct position. * @param item that is inserted */ publicvoid insert(E item){ if(s==maxS-1){ maxS=maxS*2; Object[] grownArray =newObject[maxS]; System.arraycopy(h,0, grownArray,0, h.length); h=grownArray; } h[s]=item; siftUp(s);
  • 33. s++; } /** * size returns the size of the heap. * @return the integer size of the heap */ publicint size(){ return s; } /** * siftUp, sifts the node at index i up through the heap into th e correct position. * @param i the value to begin sifting */ privatevoid siftUp(int i) { int n=i; boolean inPlace =false; if(n==0){ inPlace=true; } while(inPlace==false){ int a=(n-1)/2; E below=(E) h[n]; E above=(E) h[a]; if(c.compare(below,above)>0){ h[n]= above; h[a]=below; n=a; }else{ inPlace=true; }
  • 34. } } /** * SiftDown sifts the node at index i down to the correct spot in the heap. * @param i the value to begin sifting */ privatevoid siftDown(int i) { int n=i; boolean inPlace =false; while(inPlace==false){ int a=(n*2)+1; E above=(E) h[n]; E belowL=(E) h[a]; E belowR=(E) h[a+1]; if(belowL==null&& belowR==null){ return; } //if neither of the children are null if(belowL !=null&& belowR !=null){ //compare to the left child if(c.compare(above,belowL)<0&& c.compare(belowL,belowR)> =0){ System.out.println("down and to the left!"); h[a]= above; h[n]=belowL; n=a; //compare to the right child }elseif(c.compare(above,belowR)<0){ System.out.println("down and to the right!");
  • 35. h[a+1]= above; h[n]=belowR; n=a; //otherwise its in place }else{ System.out.println("its down in place"); inPlace=true; } //if the left child isnt null }elseif(belowL !=null){ if(c.compare(above, belowL)<0){ h[n]= above; h[a]=belowL; n=a; }else{ inPlace=true; } }else{ // if the right child isnt null compare it to the parent if(c.compare(above,belowR)<0){ h[a+1]= above; h[n]=belowR; n=a; }else{ inPlace=true; } } } }
  • 36. /** * MaxHeapComparator compares two values and prioritizes t he max value. * @author tai-lanhirabayashi * * @param <E> the comparable object */ publicstaticclassMaxHeapComparator<E extendsComparable<E >>implementsComparator<E>{ @Override publicint compare(E o1, E o2){ return o1.compareTo(o2); } } /** * MinHeapComparator compares two values and prioritizes t he lower value * @author tai-lanhirabayashi * * @param <E> the comparable object */ publicstaticclassMinHeapComparator<E extendsComparable<E> >implementsComparator<E>{ @Override publicint compare(E o1, E o2){ return(-1* o1.compareTo(o2)); } } }
  • 37. PriorityQueueTest.classpublicsynchronizedclass PriorityQueueTest { PriorityQueue p; public void PriorityQueueTest(); public void start(); public void testPeek(); public void testRemove(); public void testSize(); public void testEmpty(); } PriorityQueueTest.javaPriorityQueueTest.javaimportstatic org.j unit.Assert.*; import java.util.Comparator; import org.junit.Before; import org.junit.Test; publicclassPriorityQueueTest{ PriorityQueue p; /** * Start initialized the program, with a queue of 1,2,3,4 and a max priority. */ @Before publicvoid start(){ Comparator<Integer> c =newHeap.MaxHeapComparator(); p=newPriorityQueue(10, c); p.add(1);
  • 38. p.add(2); p.add(3); p.add(4); } /** * testPeek tests the peek function. */ @Test publicvoid testPeek(){ assertEquals(4, p.peek()); p.remove(); assertEquals(3, p.peek()); p.remove(); assertEquals(2, p.peek()); p.remove(); assertEquals(1, p.peek()); p.remove(); assertEquals(null, p.peek()); } /** * restRemove tests the remove function. */ @Test publicvoid testRemove(){ assertEquals(4, p.remove()); assertEquals(3, p.remove()); assertEquals(2, p.remove()); assertEquals(1, p.remove()); assertEquals(null, p.remove()); } /**
  • 39. * testSize tests the size function. */ @Test publicvoid testSize(){ assertEquals(4, p.size()); p.remove(); assertEquals(3, p.size()); p.remove(); assertEquals(2, p.size()); p.remove(); assertEquals(1, p.size()); p.remove(); assertEquals(0, p.size()); p.add(9); assertEquals(1, p.size()); } /** * testEmpty tests the isEmpty function of priorityQueue. */ @Test publicvoid testEmpty(){ assertFalse(p.isEmpty()); p.remove(); assertFalse(p.isEmpty()); p.remove(); assertFalse(p.isEmpty()); p.remove(); assertFalse(p.isEmpty()); p.remove(); assertTrue(p.isEmpty()); p.add(5); assertFalse(p.isEmpty()); }
  • 40. } BSTMap.classpublicsynchronizedclass BSTMap extends Map { nObject obj; BSTMap left; BSTMap right; int s; BSTMap parent; public void BSTMap(Object, Object); public void setParent(BSTMap); public BSTMap getParent(); public void setLeft(BSTMap); public void setRight(BSTMap); public BSTMap getLeft(); public BSTMap getRight(); boolean isLeaf(); } BSTMap.javaBSTMap.java publicclassBSTMap<K,V>extendsMap{ nObject obj; BSTMap<K,V> left; BSTMap<K,V> right; int s; BSTMap<K,V> parent; /** * BSTMap creates a node with a K key and V value. * @param ke the K value * @param va the V value */ publicBSTMap(K ke, V va){ obj=new nObject(ke,va); left=null;
  • 41. right=null; parent=null; } /** * setParent sets the BSTMap which is this nodes parent. * @param p the parent */ publicvoid setParent(BSTMap<K,V> p){ parent=p; } /** * getParent returns the parent of this node. * @return BSTMap that is this nodes parent. */ publicBSTMap<K,V> getParent(){ return parent; } /** * setLeft sets the BSTMap left child. * * @param child BSTMap that is this nodes child. */ publicvoid setLeft(BSTMap<K,V> child){ left=child; if(child!=null){ left.setParent(this); } } /** * setRight sets the this nodes BSTMap child. * @param child BSTMap that is this nodes child. */ publicvoid setRight(BSTMap<K,V> child){
  • 42. right=child; if(child!=null){ right.setParent(this); } } /** * getLeft returns this nodes left BSTMap child. * @return BSTMap this nodes left child */ publicBSTMap<K,V> getLeft(){ return left; } /** * getRight returns this nodes right BSTMap child. * @return BSTMap this nodes right child */ publicBSTMap<K,V> getRight(){ return right; } /** * isLeaf checks if the node is a leaf node by checking if it ha s children. * * It returns true for leaf, false for if it has children. * @return boolean if the node is a leaf node. */ boolean isLeaf(){ if(getLeft()==null&& getRight()==null){ returntrue; } returnfalse; }
  • 43. } BinaryTreeTest.classpublicsynchronizedclass BinaryTreeTest { BinaryTree t; public void BinaryTreeTest(); public void before(); public void testSetup(); public void testGetLeft(); public void testGetRight(); public void isLeaf(); public void setLeft(); public void setRight(); public void setValue(); } BinaryTreeTest.javaBinaryTreeTest.javaimportstatic org.junit.A ssert.*; import org.junit.Before; import org.junit.Test; /** * BinaryTreeTest tests to see if Binary Tree functions as expect ed. * @author tai-lanhirabayashi * */ publicclassBinaryTreeTest{ BinaryTree t; /** * before sets up a base case. */ @Before
  • 44. publicvoid before(){ t=newBinaryTree(null,"head",null); t.setLeftChild(newBinaryTree(null,"second",null)); t.getLeftChild().setLeftChild(newBinaryTree(null,"third", null)); } /** * testSetup makes sure the test has been initialized. */ @Test publicvoid testSetup(){ assertEquals(t.getValue(),"head"); } /** * tests the getLeft function */ @Test publicvoid testGetLeft(){ assertEquals(t.getLeftChild().getValue(),"second"); } /** * Tests the get right function */ @Test publicvoid testGetRight(){ assertEquals(t.getRightChild(),null); } /** * Tests the isLeaf function. */ @Test publicvoid isLeaf(){ assertEquals(t.getLeftChild().getLeftChild().isLeaf(),true);
  • 45. } /** * Tests the setLeft function */ @SuppressWarnings("unchecked") @Test publicvoid setLeft(){ t.setLeftChild(newBinaryTree(null,"replace",null)); assertEquals(t.getLeftChild().getValue(),"replace"); } /** * tests the setRightChild function */ @SuppressWarnings("unchecked") @Test publicvoid setRight(){ t.setRightChild(newBinaryTree(null,"right",null)); assertEquals(t.getRightChild().getValue(),"right"); } /** * Tests the setValue function. */ @Test publicvoid setValue(){ t.getLeftChild().setValue("reset"); assertEquals(t.getLeftChild().getValue(),"reset"); } } ArithmeticExpressionTest.classpublicsynchronizedclass ArithmeticExpressionTest { ArithmeticExpression a;
  • 46. public void ArithmeticExpressionTest(); public void startUp() throws java.text.ParseException; public void testExceptions(); public void testToString(); public void testEval(); public void testVar() throws java.rmi.NotBoundException, java.text.ParseException; public void testPostFix(); public void testWithoutSpaces() throws java.text.ParseException; } ArithmeticExpressionTest.javaArithmeticExpressionTest.javaim portstatic org.junit.Assert.*; import java.rmi.NotBoundException; import java.text.ParseException; import org.junit.Before; import org.junit.Test; /** * ArithmeticExpressionTest tests the functionality of Arithmeti cExpression. *** Note, the Program includes postFix() which returns a postfi x String of the equation. *** It can also handle strings with or without spaces. * * * @author tai-lan hirabayashi * */ publicclassArithmeticExpressionTest{ ArithmeticExpression a;
  • 47. /** * StartUp sets up the base case scenario. * @throws ParseException if the equation is not valid. */ @Before publicvoid startUp()throwsParseException{ a=newArithmeticExpression("3 + 4 * 2"); } /** * testExceptions tests the programs thrown exceptions. */ @Test publicvoid testExceptions(){ boolean errorThrown =false; try{ a=newArithmeticExpression("3 + * 2"); }catch(ParseException e){ errorThrown=true; } assert(errorThrown); errorThrown=false; try{ a.setVariable("y",2); }catch(NotBoundException e){ errorThrown=true; } assert(errorThrown); } /** * testToString tests the toString method of the ArithmeticEx pression */ @Test
  • 48. publicvoid testToString(){ System.out.println("this is toString: "+ a.toString(a.t)); assertEquals(a.toString(a.t),"((2*4)+3)"); } /** * testEval tests the evaluate method of ArithmeticExpression */ @Test publicvoid testEval(){ assertEquals(a.evaluate(a.t),11); } /** * testVar tests the setVariable function of ArithmeticExpress ion * by checking how a variable is handled. * @throws NotBoundException * @throws ParseException if the equation is not valid. */ @Test publicvoid testVar()throwsNotBoundException,ParseException{ a=newArithmeticExpression("2 + 3 * x"); assertEquals(a.evaluate(a.t),2); a.setVariable("x",2); assertEquals(a.evaluate(a.t),8); } /** * Tests the postFix() method. */ @Test publicvoid testPostFix(){ assertEquals(a.toPostfixString(a.t),"3 4 2 * +"); } @Test publicvoid testWithoutSpaces()throwsParseException{ a=newArithmeticExpression("2+3*x"); assertEquals(a.evaluate(a.t),2);
  • 49. } } nObject.classpublicsynchronizedclass nObject { Object key; Object value; public void nObject(Object, Object); public Object getKey(); public Object getValue(); public void changeKey(Object); public void changeValue(Object); } nObject.javanObject.java publicclass nObject<K,V>{ K key; V value; /** * nObject creates a new nObject object with a K,V values he ld. * @param ky the K key value * @param val the V value value. */ public nObject (K ky, V val){ key=ky; value=val; } /** * getKey returns the K key. * @return K, the key */ public K getKey(){
  • 50. return key; } /** * getValue returns the V value. * @return V value */ public V getValue(){ return value; } /** * changeK allows the user to pass in a new K key. * @param ky K to be changed to. */ publicvoid changeKey(K ky){ key=ky; } /** * changeValue allows the value to be changed. * @param val the new V value. */ publicvoid changeValue(V val){ value=val; } } BSTMapTest.classpublicsynchronizedclass BSTMapTest { BSTMap m; public void BSTMapTest(); public void startUp(); public void testGetLeft();
  • 51. public void testGetRight(); public void testGetParent(); public void testIsLeaf(); public void testSetLeft(); public void testSetRight(); public void testSetParent(); } BSTMapTest.javaBSTMapTest.javaimportstatic org.junit.Assert .*; import org.junit.Before; import org.junit.Test; publicclassBSTMapTest{ BSTMap m; /** * startUp creates a new instance of BSTMap. */ @Before publicvoid startUp(){ m=newBSTMap(1,"one"); } /** * testGetLeft tests getLeft(). * * It tests when it doesnt exist, when it does exist, when it ha s been changed, and when it has been removed. */ @Test publicvoid testGetLeft(){ assertEquals(null, m.getLeft());
  • 52. m.setRight(newBSTMap(3,"three")); assertEquals(null, m.getLeft()); BSTMap child=newBSTMap(2,"two"); BSTMap a=newBSTMap(1,"a"); m.setLeft(child); assertEquals(child, m.getLeft()); m.setLeft(a); assertEquals(a, m.getLeft()); m.setLeft(null); assertEquals(null, m.getLeft()); } /** * testGetRight tests getRight(). * * It tests when it doesnt exist, when it does exist, and when i t has been removed. */ @Test publicvoid testGetRight(){ assertEquals(null, m.getRight()); m.setLeft(newBSTMap(2,"two")); assertEquals(null, m.getRight()); BSTMap child =newBSTMap(3,"three"); BSTMap a=newBSTMap(1,"a"); m.setRight(child); assertEquals(child, m.getRight()); m.setRight(a); assertEquals(a, m.getRight()); m.setRight(null); assertEquals(null, m.getRight());
  • 53. } /** * testGetParent tests getParent() * * It tests when there is a parent, when there is not a parent. */ @Test publicvoid testGetParent(){ assertEquals(null, m.getParent()); m.setLeft(newBSTMap(2,"two")); assertEquals(null, m.getParent()); BSTMap child =newBSTMap(3,"three"); m.setRight(child); assertEquals(m, child.getParent()); } /** * testIsLeaf tests to see if a node is a leaf. * * It tests when it has no children, when it has a left child, a right child, both, and when they have been removed. */ @Test publicvoid testIsLeaf(){ assertTrue(m.isLeaf()); m.setLeft(newBSTMap(2,"two")); assertFalse(m.isLeaf()); m.setRight(newBSTMap(3,"three")); assertFalse(m.isLeaf()); m.setLeft(null); assertFalse(m.isLeaf()); m.setRight(null);
  • 54. assertTrue(m.isLeaf()); } /** * testSetLeft tests setLeft() * */ @Test publicvoid testSetLeft(){ assertEquals(null, m.getLeft()); BSTMap child=newBSTMap(2,"two"); m.setLeft(child); m.setRight(newBSTMap(3,"three")); assertEquals(child,m.getLeft()); m.setLeft(null); assertEquals(null,m.getLeft()); } /** * testSetRight tests setRight */ @Test publicvoid testSetRight(){ BSTMap child=newBSTMap(2,"two"); BSTMap a=newBSTMap(1,"a"); assertEquals(null, a.getRight()); a.setRight(child); assertEquals(child, a.getRight()); a.setRight(null); assertEquals(null, a.getRight()); } /**
  • 55. * testSetParent tests setParent */ @Test publicvoid testSetParent(){ BSTMap child=newBSTMap(2,"two"); BSTMap a=newBSTMap(1,"a"); assertEquals(null, a.getParent()); a.setParent(child); assertEquals(child, a.getParent()); a.setParent(null); assertEquals(null, a.getParent()); } } HTree.classpublicsynchronizedclass HTree { private String s; private int f; HTree l; HTree r; public void HTree(int, String); public void setL(HTree); public void setR(HTree); public HTree getL(); public HTree getR(); public String getS(); public int getF(); public boolean isLeaf(); public int getBelow(); } HTree.javaHTree.java publicclassHTree<E extendsComparable<E>>{
  • 56. privateString s; privateint f; HTree l; HTree r; /** * HTree creates a HTree object containing a int frequency an d a String str. * @param frequency the integer frequency of the str * @param str the str value of this HTree */ publicHTree(int frequency,String str){ s=str; f=frequency; l=null; r=null; } /** * setL sets the left HTree value * @param left the HTree that is the left child of this node */ publicvoid setL(HTree left){ l=left; } /** * setR sets the right HTree child value * @param right the HTree that is the right child of this node */ publicvoid setR(HTree right){ r=right; } /**
  • 57. * getL returns the left child of this node. * @return HTree the left child. */ publicHTree getL(){ return l; } /** * getR returns the right child of this node. * @return HTree the right child. */ publicHTree getR(){ return r; } /** * getS returns the string value associated with this node * @return String the value of this node */ publicString getS(){ return s; } /** * getF returns the frequency value associated with this node. * @return the int frequency value associated with this node. */ publicint getF(){ return f; } /** * isLeaf returns boolean if this node is a leaf. * @return boolean wether this node is a leaf. */ publicboolean isLeaf(){
  • 58. if(l==null&&r==null){ returntrue; } returnfalse; } /** * getBelow recursively finds how many children this node h as. * * **this does not handle trees with only one child (as this do es not occur in a huffmanTree) * @return the int number height */ publicint getBelow(){ if(isLeaf()){ return0; }else{ int a=1+l.getBelow(); int b=1+r.getBelow(); if(a>b){ System.out.println("returning a: "+ a); return a; } System.out.println("returning b"+ b); return b; } } } HeapTest.classpublicsynchronizedclass HeapTest { Heap h;
  • 59. Heap min; public void HeapTest(); public void start(); public void testFindMax(); public void testRemoveMax(); public void testSize(); public void testMin(); } HeapTest.javaHeapTest.javaimportstatic org.junit.Assert.*; import java.util.Comparator; import org.junit.Before; import org.junit.Test; publicclassHeapTest{ Heap h; Heap min; /** * start creates a test case of heap both min and max compara tor. */ @Before publicvoid start(){ Comparator<Integer> c =newHeap.MaxHeapComparator<Intege r>(); Comparator<Integer> m =newHeap.MinHeapComparator<Intege r>(); min=newHeap(10,m); min.insert(1); min.insert(2); min.insert(3);
  • 60. min.insert(4); h=newHeap(10,c); System.out.println("this is 1"); h.insert(1); System.out.println(h.h[0]); System.out.println("this is 2"); h.insert(2); System.out.println(h.h[0]+","+h.h[1]); System.out.println("this is 3"); h.insert(3); System.out.println(h.h[0]+","+h.h[1]+","+h.h[2]); System.out.println("this is 4"); h.insert(4); System.out.println(h.h[0]+","+h.h[1]+","+h.h[2]+","+h.h[3]); } /** * testFindMax tests the findMax function */ @Test publicvoid testFindMax(){ assertEquals(4, h.findMax()); assertEquals(4, h.removeMax()); assertEquals(3, h.findMax()); assertEquals(1, min.findMax()); assertEquals(1, min.removeMax()); assertEquals(2, min.findMax()); } /** * testRemoveMax tests the remove max function
  • 61. */ @Test publicvoid testRemoveMax(){ assertEquals(4, h.findMax()); assertEquals(4,h.removeMax()); assertEquals(3, h.findMax()); assertEquals(3,h.removeMax()); assertEquals(2,h.removeMax()); assertEquals(1,h.removeMax()); assertEquals(0,h.size()); assertEquals(1, min.findMax()); } /** * testSize tests the size function of heap. */ @Test publicvoid testSize(){ assertEquals(4, h.size()); int o=(Integer) h.removeMax(); assertEquals(3, h.size()); h.insert(o); assertEquals(4, h.size()); h.removeMax(); h.removeMax(); h.removeMax(); h.removeMax(); assertEquals(0, h.size()); assertEquals(4, min.size()); } /** * testMin tests the minSort comparator. */
  • 62. @Test publicvoid testMin(){ assertEquals(4, min.size()); assertEquals(1,min.removeMax()); assertEquals(2,min.removeMax()); assertEquals(3,min.removeMax()); assertEquals(4,min.removeMax()); } } HuffmanTree$CountPair.classsynchronizedclass HuffmanTree$CountPair { int _count; String _text; private void HuffmanTree$CountPair(HuffmanTree, String, int); } HuffmanTree$CountPairTreeComparator.classsynchronizedclass HuffmanTree$CountPairTreeComparator implements java.util.Comparator { private void HuffmanTree$CountPairTreeComparator(HuffmanTree); public int compare(BinaryTree, BinaryTree); } HuffmanTree.classpublicsynchronizedclass HuffmanTree { java.io.File current; BSTMap _lookupTable;
  • 63. BinaryTree _huffmanTree; public void HuffmanTree(); publicstatic HuffmanTree newTreeFromFile(java.io.File) throws java.io.FileNotFoundException; publicstatic HuffmanTree newTreeFromCompressedFile(java.io.File) throws java.io.FileNotFoundException; private void buildFromFile(java.io.File) throws java.io.FileNotFoundException; private void buildTreeFromMap(PriorityQueue); private void buildFromCompressedFile(java.io.File) throws java.io.FileNotFoundException; public void saveCompressedFile(java.io.File); public void saveExpandedFile(java.io.File); public String encode(String); public String decode(String); } HuffmanTree.javaHuffmanTree.javaimport java.io.File; import java.io.FileNotFoundException; import java.util.Comparator; import java.util.Scanner; import java.util.Set; /** * This class implements the basic functionality of Huffman co mpression and expansion. * * @author C. Andrews * */ publicclassHuffmanTree{ File current; BSTMap<String,String> _lookupTable =newBSTMap<String,Str
  • 64. ing>(null,null); BinaryTree<CountPair> _huffmanTree; /** * This is a factory method for reading in a fresh text file to i nitialize the Huffman tree. * * @param file the document to use for the code frequencies * @return a HuffmanTree containing the Huffman codes bas ed on the frequencies observed in the document * @throws FileNotFoundException */ publicstaticHuffmanTree newTreeFromFile(File file)throwsFile NotFoundException{ HuffmanTree tree =newHuffmanTree(); tree.buildFromFile(file); return tree; } /** * This is a factory method that builds a new HuffmanTree fr om a compressed file. * * @param file a file that has been compressed with a Huffma n tool * @return a new HuffmanTree containing the codes for deco ding the file * @throws FileNotFoundException */ publicstaticHuffmanTree newTreeFromCompressedFile(File file )throwsFileNotFoundException{ // TODO implement this }
  • 65. /** * This method builds the Huffman tree from the input file. * * @param file the file to use to construct the Huffman tree * @throws FileNotFoundException */ privatevoid buildFromFile(File file)throwsFileNotFoundExcepti on{ current=file; // read file and build the map of the character frequencies Map<String,Integer> freqMap =newBSTMap<String,Integer>(); Scanner scanner =newScanner(file); scanner.useDelimiter(""); String character; while(scanner.hasNext()){ character = scanner.next(); Integer count = freqMap.get(character); if(count ==null){ count =Integer.valueOf(0); } freqMap.put(character, count+1); } // for each key, make a tree and load it into the priority queue PriorityQueue<BinaryTree<CountPair>> treeQueue =newPriorit yQueue<BinaryTree<CountPair>>(freqMap.keySet().size(),new CountPairTreeComparator()); BinaryTree<CountPair> tmpTree; for(String key: freqMap.keySet()){
  • 66. int frequency = freqMap.get(key); tmpTree =newBinaryTree<CountPair>(null,newCountPa ir(key, frequency),null); treeQueue.add(tmpTree); } // while the size of the priority queue is greater than 1, combine the top items into a tree and put them back in the priority queue BinaryTree<CountPair> tree1, tree2; int newFrequency; String newText; while(treeQueue.size()>1){ tree1 = treeQueue.remove(); tree2 = treeQueue.remove(); // If the height of the second tree is less than the height of the fi rst, // or the heights are the same and tree2 precedes tree1 alphabeti cally, swap them so // the smaller/earlier tree is put on the left if(tree1.getValue()._text.length()> tree2.getValue()._text.length () ||( tree1.getValue()._text.length()== tree2.getValue()._text.lengt h() && tree1.getValue()._text.compareTo(tree2.getValue()._text)>0 )){ tmpTree = tree1; tree1 = tree2; tree2 = tmpTree; } // create a new tree combining the two smaller trees, computing a new frequency that is the sum of the // children frequencies and a new text that is the appended comb ination of the children's text newFrequency = tree1.getValue()._count + tree2.getVal ue()._count;
  • 67. newText = tree1.getValue()._text + tree2.getValue()._te xt; tmpTree =newBinaryTree<CountPair>(tree1,newCountP air(newText, newFrequency), tree2); treeQueue.add(tmpTree); } // pull the completed tree from the priority queue BinaryTree<CountPair> tree = treeQueue.remove(); // create map of symbols to code lengths using the tree Map<String,Integer> codeLengthMap =newMap<String,Integer> (); // TODO implement this part PriorityQueue pq=newPriorityQueue(setC.size(),new treeCompa rator()); buildTreeFromMap(pq); } privatevoid buildTreeFromMap(PriorityQueue q){ // TODO Auto-generated method stub } /** * Builds the tree using information found in a compressed fil e. * * The table is the first thing we find in the file. The first pie ce of data is the length * of the table (L). This is followed by L pairs of character an
  • 68. d code length pairs. * * @param file the file to read the Huffman code from. */ privatevoid buildFromCompressedFile(File file)throwsFileNotF oundException{ // TODO implement this } /** * Read the original file and compress it using the Huffman cod es, writing the result * into the output file. * * @param outputFile the output file */ publicvoid saveCompressedFile(File outputFile){ // TODO implement this } /** * Read the compressed file that initialized this object and wr ite the decoded version out * into the output file. * * @param outputFile the destination file for the uncompress ed file. */ publicvoid saveExpandedFile(File outputFile){ // TODO implement this }
  • 69. /** * This method reads in a String of text and returns a String o f 0s and 1s corresponding to the Huffman code stored in this tre e. * @param text the text to be encoded * @return a String representation of the Huffman code */ publicString encode(String text){ StringBuilder builder =newStringBuilder(); String tmp; for(int i =0; i < text.length(); i++){ tmp = _lookupTable.get(String.valueOf(text.charAt(i))); builder.append(tmp); } return builder.toString(); } /** * This method reads in a String representation of a Huffman code corresponding to this Huffman tree and decodes it. * @param text a String representation of the a Huffman code d message * @return the original text */ publicString decode(String text){ StringBuilder builder =newStringBuilder(); BinaryTree<CountPair> current = _huffmanTree; for(int i =0; i < text.length(); i++){ char c = text.charAt(i); if(c =='0'){ current = current.getLeftChild(); }elseif(c =='1'){
  • 70. current = current.getRightChild(); }else{ thrownewRuntimeException("Encountered unexpected character in coded String"); } if(current.isLeaf()){ builder.append(current.getValue()._text); current = _huffmanTree; } } return builder.toString(); } privateclassCountPair{ int _count; String _text; privateCountPair(String text,int count){ _text = text; _count = count; } } privateclassCountPairTreeComparatorimplementsComparator<B inaryTree<CountPair>>{ @Override publicint compare(BinaryTree<CountPair> t1,BinaryTree<Coun tPair> t2){ CountPair p1 = t1.getValue(); CountPair p2 = t2.getValue();
  • 71. if(p1._count != p2._count){ return p2._count - p1._count; }elseif(p1._text.length()!= p2._text.length()){ return-p1._text.length()- p2._text.length(); }else{ return p1._text.compareTo(p2._text); } } } } nObjectTest.classpublicsynchronizedclass nObjectTest { nObject o; public void nObjectTest(); public void setUp(); public void testChangeKey(); public void testChangeValue(); public void testGetKey(); public void testGetValue(); } nObjectTest.javanObjectTest.javaimportstatic org.junit.Assert.* ; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test;
  • 72. publicclass nObjectTest { nObject o; /** * setUp sets up the test. */ @Before publicvoid setUp(){ o=new nObject("one",1); } /** * tests the change Key function */ @Test publicvoid testChangeKey(){ assertEquals("one", o.getKey()); o.changeKey("two"); assertEquals("two", o.getKey()); } /** * tests the change Value function */ @Test publicvoid testChangeValue(){ assertEquals(1, o.getValue()); o.changeValue(2); assertEquals(2, o.getValue()); } /** * testGetKey tests the getKey method */ @Test publicvoid testGetKey(){
  • 73. assertEquals("one", o.getKey()); o.changeKey("two"); assertEquals("two", o.getKey()); } /** * testGetValue tests get Value */ @Test publicvoid testGetValue(){ assertEquals(1, o.getValue()); o.changeValue(2); assertEquals(2, o.getValue()); } } MapTest.classpublicsynchronizedclass MapTest { Map m; public void MapTest(); public void start(); public void testContainsKey(); public void testGet(); public void testKeySet(); public void testPut(); public void testRemove(); } MapTest.javaMapTest.javaimportstatic org.junit.Assert.*; import org.junit.Before; import org.junit.Test;
  • 74. publicclassMapTest{ Map m; /** * start() creates an initial map to test. */ @Before publicvoid start(){ m=newMap(); } /** * testContainsKey tests the containsKey function. * It tests when there are more than one object, one object, * when the object is contained, and when the object is not co ntained. */ @Test publicvoid testContainsKey(){ assertFalse(m.containsKey(5)); m.put(5,"five"); m.put(4,"four"); assertTrue( m.containsKey(5)); m.remove(5); assertFalse(m.containsKey(5)); m.remove(4); assertFalse(m.containsKey(4)); } /** * testGet tests the get function of map. *
  • 75. * It tests when there are no objects, when there is an object, and when there are more than one objects. */ @Test publicvoid testGet(){ assertEquals(null, m.get(5)); m.put(5,"five"); assertEquals("five",m.get(5)); m.put(4,"four"); assertEquals("five",m.get(5)); } /** * testKeySet tests keySet. */ @Test publicvoid testKeySet(){ assertEquals(true, m.keySet().isEmpty()); m.put(5,"five"); assertEquals(false, m.keySet().isEmpty()); assertEquals(true, m.keySet().contains(5)); } /** * testPut tests the put method of map. */ @Test publicvoid testPut(){ assertEquals(null, m.get(5)); m.put(5,"five"); assertEquals("five",m.get(5)); m.put(5,"changed"); m.put(6,"six"); assertEquals("changed",m.get(5)); assertEquals("six",m.get(6));
  • 76. } /** * testRemove tests map's remove function * * It tests if it can remove something that isnt in map, and re moval of objects not in order. */ @Test publicvoid testRemove(){ assertEquals(null, m.remove("a")); m.put(5,"five"); m.put(4,"four"); m.put(3,"three"); assertEquals("three", m.remove(3)); assertEquals("five", m.remove(5)); assertEquals("four", m.remove(4)); } } .project assignment 8 org.eclipse.jdt.core.javabuilder
  • 77. org.eclipse.jdt.core.javanature META-INF/MANIFEST.MF Manifest-Version: 1.0 .classpath PriorityQueue.classpublicsynchronizedclass PriorityQueue { Heap q; public void PriorityQueue(int, java.util.Comparator); public Object peek(); public Object remove(); void add(Object); boolean isEmpty(); public int size(); } PriorityQueue.javaPriorityQueue.javaimport java.util.Comparat or; publicclassPriorityQueue<E>{
  • 78. Heap q; /** *PriorityQueue initializes the queue. * * @param initialCapacity an int that is the heaps initial size. * @param comparator the priority of various imputs. */ publicPriorityQueue(int initialCapacity,Comparator<?super E> comparator){ q=newHeap(initialCapacity,comparator); } /** * Peek, returns the next item in the queue without removing it. * * If it is empty then null is returned. * @return the next item in the queue. */ public E peek(){ if(q.size()==0){ returnnull; } return(E) q.findMax(); } /** * This removes the first item from the queue. * * It returns null if the queue is empty. * @return the first item in the queue. */ public E remove(){ if(q.size()==0){ returnnull;
  • 79. } return(E) q.removeMax(); } /** * This adds item to the queue * @param item that is added to the queue. */ void add(E item){ q.insert(item); } /** * isEmpty returns if the queue is empty or not. * * @return boolean if the queue is empty or not. */ boolean isEmpty(){ if(q.size()!=0){ returnfalse; } returntrue; } /** * size returns the size of the queue. * * @return int the size of the queue. */ publicint size(){ return q.size(); } } ArithmeticExpression.classpublicsynchronizedclass
  • 80. ArithmeticExpression { BinaryTree t; java.util.ArrayList list; String equation; void ArithmeticExpression(String) throws java.text.ParseException; public String toString(BinaryTree); public String toPostfixString(BinaryTree); void setVariable(String, int) throws java.rmi.NotBoundException; public int evaluate(BinaryTree); } ArithmeticExpression.javaArithmeticExpression.javaimport java .rmi.NotBoundException; import java.text.ParseException; import java.util.ArrayList; import java.util.Stack; /** * ArithmeticExpression takes equations in the form of strings c reates a binary * tree, and can return either the regular or postfix equation. It a lso allows * them to be calculated. * * * Extra Credit: * ** it can handle spaces or no spaces in the string inputted. ** it can return * regular or postfix notation * * @author tai-lanhirabayashi * */
  • 81. publicclassArithmeticExpression{ BinaryTree t; ArrayList list; String equation; /** * ArithmeticExpression is the construction which takes in a space * delimitated equation containing "*,/,+,- " symbols and converts it into a * binary tree. * * If the expression is not valid it will throw a ParseExceptio n. This is * the constructor. It will take a String containing the express ion. * * ** The equation can take in stings delimitated by spaces, o r withot any * spaces. If it contains a mix, then the non spaced part(s) wil l be * considered to be a variable. * * @param expression * @throws ParseException * if the string is not a valid equation */ @SuppressWarnings({"unchecked","rawtypes"}) ArithmeticExpression(String expression)throwsParseException{ //hold the string globally equation = expression; //create a new arrayList to be used globally that holds the variab les
  • 82. list =newArrayList(); //split the string String[] s = expression.split(" "); // create a stack of tree's and operators Stack tree =newStack(); Stack operator =newStack(); //create the string Next String next =""; // if the string expression doesnt contain spaces if(!expression.contains(" ")){ int i =0; //if it starts with an operator throw an error this cannot be. if(expression.charAt(0)=='+'|| expression.charAt(0)=='*' || expression.charAt(0)=='-' || expression.charAt(0)=='/'){ System.out.println("this equation starts with a operator."); thrownewParseException(expression,0); } // if the expression ends with an operator throw an error this can not be. if(expression.charAt(expression.length()-1)=='+' || expression.charAt(expression.length()-1)=='*' || expression.charAt(expression.length()-1)=='-' || expression.charAt(expression.length()-1)=='/'){ System.out.println("this equation ends with a operator."); thrownewParseException(expression, expression.length()); } //go through each characer in the expression and see if its a num ber/variable, or operator.
  • 83. while(i < expression.length()){ if(expression.charAt(i)=='+'|| expression.charAt(i)=='*' || expression.charAt(i)=='-' || expression.charAt(i)=='/'){ // if the character is a operator add a space to the begining and f ront and add it to the "next" string String str =String.valueOf(expression.charAt(i)); next = next +" "+ str +" "; }else{ // if its an operator add it to the end of the "next" string. next = next + expression.charAt(i); } // increase i to move to the next character. i++; } // split the new string with added spaces. s = next.split(" "); } // if the string still doesnt exist throw the error. if(s.length ==0){ System.out .println("there has been an error. You have not entered a string with any characters"); thrownewParseException(expression,0); } // make sure there arent two operators in a row. for(int i =0; i < s.length; i++){ if(i >=1 &&(s[i].equals("+")|| s[i].equals("-") || s[i].equals("*")|| s[i].equals("/"))){
  • 84. if(s[i -1].equals("+")|| s[i -1].equals("-") || s[i -1].equals("*")|| s[i -1].equals("/")){ System.out .println("there were two operators in a row. The equation is not valid."); thrownewParseException(expression, i); } } // check to make sure there arent two operands in a row in the St ring[] if(i >=1 &&(s[i].equals("+")==false&& s[i].equals("-")==false && s[i].equals("*")==false&& s[i].equals("/")==false)){ if(s[i -1].equals("+")==false && s[i -1].equals("-")==false && s[i -1].equals("*")==false && s[i -1].equals("/")==false){ System.out .println("there were two operands in a row. The equation is not valid."); thrownewParseException(expression, i); } } // if its a number create a new tree node, and add it to the tree st ack if(s[i].equals("+")==false&& s[i].equals("-")==false && s[i].equals("*")==false&& s[i].equals("/")==false){ BinaryTree o =newBinaryTree(null, s[i],null); tree.add(o); }elseif(operator.empty()|| s[i].equals("*")|| s[i].equals("/")){ //if its a * or / symbol hold it to ensure order of operation
  • 85. operator.push(s[i]); }else{ //group the tree's together. while(operator.empty()==false){ String operatorHeld =(String) operator.pop(); BinaryTree one =(BinaryTree) tree.pop(); BinaryTree two =(BinaryTree) tree.pop(); BinaryTree n =newBinaryTree(one, operatorHeld, two); tree.push(n); } operator.push(s[i]); } } // at the end ensure that the operator is empty. while(operator.empty()==false){ String operatorHeld =(String) operator.pop(); BinaryTree one =(BinaryTree) tree.pop(); BinaryTree two =(BinaryTree) tree.pop(); BinaryTree n =newBinaryTree(one, operatorHeld, two); tree.push(n); } //if there is more than 1 tree at the end something went wrong // this should not occur as it should have been caught earlier // this is just to ensure completeness. if(tree.size()>=2){ System.out .println("this expression is invalid. There were more operands t han operators."); System.out .println("this should not occur it should have been caught earlie r"); while(tree.empty()==false){ return;
  • 86. } } //if there are still operators there is something wrong // this should not occur as it should have been caught earlier // this is just to ensure completeness. if(operator.empty()==false){ System.out .println("this should not occur it should have been caught earlie r."); System.out .println("there were too many operators in the string the progra m cannot continue."); { return; } } // set the tree globally t =(BinaryTree) tree.pop(); } /** * toString returns the String equation of that the passed in bi nary tree * represents. * * @param tree * that represents an equation * @return the String that is represented by the passed in Bin aryTree. */ @SuppressWarnings("rawtypes") publicString toString(BinaryTree tree){
  • 87. // if its a leaf return its value if(tree.isLeaf()==true){ return(String) tree.getValue(); }else{ //else combine each parent child combination //call recursively, and contain each call in parenthesis. String s =("("+ toString(tree.getLeftChild())+ tree.getValue() + toString(tree.getRightChild())+")"); return s; } } /** * toPostfixString returns the string containing the parsed exp ression in * postFix notation with spaces between numbers and operato rs to ensure clarity. * * @param tree that represents an equation * @return the String that is represented by the passed in Bin aryTree in * postfix form. */ @SuppressWarnings("unchecked") publicString toPostfixString(BinaryTree tree){ //if its a leaf return its value if(tree.isLeaf()==true){ return(String) tree.getValue(); }else{ //otherwise call recursively down the tree // and add the operator to the end of the two operands. // also add spaces to allow numbers to be seen individually. String s = toPostfixString(tree.getRightChild())+" "
  • 88. + toPostfixString(tree.getLeftChild())+" " + tree.getValue(); System.out.println("this is what s is "+ s); return s; } } /** * This allows the user to set a value for a variable in the exp ression. If * the variable does not exist in the function, throw a NotBou ndException. * * @param name of the variable * @param value that the variable has * @throws NotBoundException if the variable is not used in the equation */ void setVariable(String name,int value)throwsNotBoundExcepti on{ //Note var, is not a Var it is a seperate class that is an object. //if the equation string doesnt contain the variable throw an erro r if(!equation.contains(name)){ thrownewNotBoundException(); } // else continue and check if the var object is already in the list for(int i =0; i < list.size(); i++){ var v =(var) list.get(i); if(v.getName().equals(name)){ //if so change the value of the var object
  • 89. v.setValue(value); return; } } // otherwise add the var object to the list. list.add(new var(name, value)); } /** * Evaluate returns the integer result of the expression. * * Variables that are not declared are calculated at 0. * * @return the value of the equation */ @SuppressWarnings("unused") publicint evaluate(BinaryTree tree){ //if it is a leaf if(tree.isLeaf()==true){ String s =(String) tree.getValue(); //if all characters are numbers simply skip down to return the in teger value. for(int i =0; i < s.length(); i++){ if(s.charAt(i)=='0'|| s.charAt(i)==('1') || s.charAt(i)=='2'|| s.charAt(i)=='3' || s.charAt(i)=='4'|| s.charAt(i)=='5' || s.charAt(i)=='6'|| s.charAt(i)=='7' || s.charAt(i)=='8'|| s.charAt(i)=='9'){ }else{ //if there are non numeric characters check if the list has their v alues
  • 90. for(int j =0; j < list.size(); j++){ var h =(var) list.get(j); if(h.getName().equals(s)){ return h.getValue(); } } //otherwise tell the user that this variable cannot be found and t hat its value is calulated at 0 System.out.println("this variable "+ s +" cannot be found! Its value will be 0."); return0; } returnInteger.parseInt((String) tree.getValue()); } } //find the left and right values of the tree int left = evaluate(tree.getLeftChild()); int right = evaluate(tree.getRightChild()); //calculate appropriately. if(tree.getValue().equals("*")){ return left * right; }elseif(tree.getValue().equals("/")){ return left / right; }elseif(tree.getValue().equals("+")){ return left + right; } return left - right; }
  • 91. } Map.classpublicsynchronizedclass Map { BSTMap root; BSTMap found; java.util.TreeSet set; public void Map(); public void put(Comparable, Object); public Object get(Comparable); public boolean containsKey(Comparable); private BSTMap getBSTMap(Comparable); public Object remove(Comparable); private BSTMap sucessor(BSTMap); public java.util.Set keySet(); } Map.javaMap.javaimport java.util.Set; import java.util.TreeSet; publicclassMap<K extendsComparable<K>,V>{ BSTMap root; BSTMap found; TreeSet<K> set; /** * Map initializes the map. */ publicMap(){ set=newTreeSet<K>(); root=null; found=null;
  • 92. } /** * put loads the Key and value into a BSTMap object, and the key into the set. * * If the key already exists the value is changed to the new va lue. * @param key the K key value * @param value the V value value */ publicvoid put(K key, V value){ //if the root is null this is the root if(root==null){ root=newBSTMap(key,value); set.add(key); //if the key exists then change the value }elseif(get(key)!=null){ getBSTMap(key).obj.value=value; }else{ //otherwise create a new BSTMap BSTMap i =newBSTMap(key,value); //add it to the set set.add(key); //and find its place in the BSTmap tree.No key can be identical. boolean done=false; BSTMap c= root; while(done==false){ //if it is bigger go right
  • 93. if(key.compareTo((K) c.obj.getKey())>=0){ if(c.getRight()==null){ c.setRight(i); done=true; }else{ c=c.getRight(); } //if it is smaller go left. }elseif(key.compareTo((K) c.obj.getKey())<0){ if(c.getLeft()==null){ c.setLeft(i); done=true; }else{ c=c.getLeft(); } } } } } /** * This finds the value associated with they key. If this key c annot be found null is returned. * @param key the K key value * @return V the associated V value. */ public V get(K key){ BSTMap current= root; if(root==null){ returnnull; } while(current!=null&& current.obj.getKey().equals(key)==false
  • 94. ){ if(key.compareTo((K) current.obj.getKey())<0){ current=current.getLeft(); }else{ current=current.getRight(); } } if(current==null){ returnnull; } if(current.obj.getKey().equals(key)){ return(V) current.obj.getValue(); } returnnull; } /** *containsKey returns boolean if the key exists in the map. * @param key the K key value to look for * @return boolean if it exists */ publicboolean containsKey(K key){ BSTMap current= root; if(root==null){ returnfalse; } while(current!=null&& current.obj.getKey().equals(key)==false ){ if(key.compareTo((K) current.obj.getKey())<0){ current=current.getLeft(); }else{ current=current.getRight(); } } if(current==null){ returnfalse;
  • 95. } return current.obj.getKey().equals(key); } /** * getBSTMap returns the BSTMap associated with a key val ue * @param key the K key value * @return BSTMap contained the K key. */ privateBSTMap getBSTMap(K key){ BSTMap current= root; if(root==null){ returnnull; } while(current!=null&& current.obj.getKey().equals(key)==false ){ if(key.compareTo((K) current.obj.getKey())<0){ current=current.getLeft(); }else{ current=current.getRight(); } } if(current.obj.getKey().equals(key)){ return current; } returnnull; } /** * remove removes the BSTMap associated with they key, an d returns its associated value. * * If the key cannot be found null is returned * @param key the K key value to be found * @return V the value of associated with the BSTMap contai
  • 96. ning the K key value. */ public V remove(K key){ if(root==null){ returnnull; }elseif(root.obj.getKey().equals(key)){ System.out.println("the node to remove is the root."); V val=(V) root.obj.getValue(); if(root.isLeaf()){ root=null; }elseif(root.getLeft()==null){ root=root.getRight(); }elseif(root.getRight()==null){ root=root.getLeft(); }else{ root=sucessor(root); } return val; } BSTMap n= getBSTMap(key); if(n==null){ returnnull; }else{ set.remove(key); V a=(V) n.obj.getValue(); BSTMap temp=null; BSTMap child=null; if(n.isLeaf()){ temp=n; n=null; }elseif(n.getLeft()!=null&& n.getLeft().getRight()==null){ temp=n; n.getLeft().setRight(n.right); n.setLeft(null); }elseif(n.getRight()!=null&& n.getRight().getLeft()==null){
  • 97. temp=n; n.getRight().setLeft(n.getLeft()); n.setRight(null); }else{ temp=sucessor(n); n.setRight(null); } System.out.println("this is the temp:"+ temp.obj.key); if(temp.getLeft()!=null){ child=temp.getLeft(); }else{ child=temp.getRight(); }if(child!=null){ child.parent=temp.parent; }if(temp.parent.getLeft()==temp){ temp.parent.setLeft(child); }else{ temp.parent.setRight(child); } return a; } } privateBSTMap sucessor(BSTMap n){ boolean running=true; BSTMap current=n.getRight(); while(running){ if(current.getLeft()!=null){ current=current.getLeft(); }else{ running=false; } } return current;
  • 98. } /** * keySet returns a Set of the K key values in the map. * @return */ publicSet<K> keySet(){ return set; } } BinaryTree.classpublicsynchronizedclass BinaryTree { Object v; BinaryTree treeLeft; BinaryTree treeRight; void BinaryTree(BinaryTree, Object, BinaryTree); BinaryTree getLeftChild(); BinaryTree getRightChild(); void setLeftChild(BinaryTree); void setRightChild(BinaryTree); void setValue(Object); Object getValue(); boolean isLeaf(); } BinaryTree.javaBinaryTree.java /** * BinaryTree is a form of linked nodes that form a tree. * * @author tai-lan hirabayashi * * @param <E> the object value that is within each node.
  • 99. */ publicclassBinaryTree<E>{ E v; BinaryTree<E> treeLeft; BinaryTree<E> treeRight; /** * BinaryTree creates a new node binaryTree which holds an object value. * It takes in the value, left and right child and holds them wi thin the node. * @param left the left child of the node. * @param value the object the node holds * @param right the right child of the node */ BinaryTree(BinaryTree<E> left, E value,BinaryTree<E> right){ v=value; treeLeft=left; treeRight=right; } /** * getLeftChild returns the left child node. * @return the left child, a binary tree node. */ BinaryTree<E> getLeftChild(){ return treeLeft; } /** * getRightChild returns the right child node. * @return the right child,a binaryTree node. */ BinaryTree<E> getRightChild(){ return treeRight;
  • 100. } /** * setLeftChild, sets the left child of the current node. * @param l is the left child, a binaryTree node. */ void setLeftChild(BinaryTree<E> l){ treeLeft=l; } /** * setRightChild, sets the right child of the current node. * @param r the right child, a binaryTree node. */ void setRightChild(BinaryTree<E> r){ treeRight=r; } /** * setValue sets the value of a node. * @param object value of the node. */ void setValue(E object){ v=object; } /** * getValue returns the value held in the node. * @return the object value of the node. */ E getValue(){ return v; } /** * isLeaf checks if the node is a leaf node by checking if it ha
  • 101. s children. * @return boolean if the node is a leaf node. */ boolean isLeaf(){ if(getLeftChild()==null&& getRightChild()==null){ returntrue; } returnfalse; } } HuffmanTreeTest.classpublicsynchronizedclass HuffmanTreeTest { HuffmanTree h; String t; public void HuffmanTreeTest(); public void start() throws java.io.FileNotFoundException; public void testEncode(); public void testDecode(); } HuffmanTreeTest.javaHuffmanTreeTest.java importstatic org.junit.Assert.*; import java.io.File; import java.io.FileNotFoundException; import org.junit.Before; import org.junit.Test; publicclassHuffmanTreeTest{ HuffmanTree h;
  • 102. String t; /** * start creates a test case * @throws FileNotFoundException */ @Before publicvoid start()throwsFileNotFoundException{ h =HuffmanTree.newTreeFromFile(newFile("/Users/tai- lanhirabayashi/Desktop/test.txt")); } /** * testEncode tries to encode a string. */ @Test publicvoid testEncode(){ t = h.encode("This program must work!"); } /** * testDecode tries to decode the string. */ @Test publicvoid testDecode(){ assertEquals("This program must work!", h.decode(t)); } } HTreeTest.classpublicsynchronizedclass HTreeTest { HTree t;
  • 103. public void HTreeTest(); public void start(); public void testGetBelow(); public void testGetF(); public void testGetS(); public void testGetL(); public void testGetR(); public void testIsLeaf(); public void testSetL(); public void testSetR(); } HTreeTest.javaHTreeTest.javaimportstatic org.junit.Assert.*; import org.junit.Before; import org.junit.Test; publicclassHTreeTest{ HTree t; /** * Start initializes a test case of HTree */ @Before publicvoid start(){ t=newHTree(1,"one"); HTree a=newHTree(2,"two"); HTree b=newHTree(3,"three"); t.setL(a); t.setR(b); } /**
  • 104. * testGetBelow tests GetBelow */ @Test publicvoid testGetBelow(){ assertEquals(1,t.getBelow()); assertEquals(0,t.getL().getBelow()); HTree a=newHTree(4,"a"); HTree b=newHTree(5,"b"); t.getL().setL(a); t.getL().setR(b); assertEquals(2,t.getBelow()); } /** * testGetF tests getF */ @Test publicvoid testGetF(){ assertEquals(1,t.getF()); assertEquals(2,t.getL().getF()); assertEquals(3,t.getR().getF()); } /** * testGetS tests getS */ @Test publicvoid testGetS(){ assertEquals("one",t.getS()); assertEquals("two",t.getL().getS()); assertEquals("three",t.getR().getS()); } /**
  • 105. * testGetL tests getL */ @Test publicvoid testGetL(){ assertEquals(2,t.getL().getF()); assertEquals(null,t.getL().getL()); } /** * testGetR tests getR */ @Test publicvoid testGetR(){ assertEquals(3,t.getR().getF()); assertEquals(null,t.getR().getR()); } /** * testIsLeaf tests isLeaf */ @Test publicvoid testIsLeaf(){ assertEquals(false,t.isLeaf()); assertEquals(true,t.getR().isLeaf()); assertEquals(true,t.getL().isLeaf()); } /** * testSetL tests setL */ @Test publicvoid testSetL(){ assertEquals(2,t.getL().getF()); t.setL(null);
  • 106. assertEquals(null,t.getL()); } /** * testSetR tests setR */ @Test publicvoid testSetR(){ assertEquals(3,t.getR().getF()); t.setR(null); assertEquals(null,t.getR()); } } Heap$MaxHeapComparator.classpublicsynchronizedclass Heap$MaxHeapComparator implements java.util.Comparator { public void Heap$MaxHeapComparator(); public int compare(Comparable, Comparable); } Heap$MinHeapComparator.classpublicsynchronizedclass Heap$MinHeapComparator implements java.util.Comparator { public void Heap$MinHeapComparator(); public int compare(Comparable, Comparable); } Heap.classpublicsynchronizedclass Heap { int s; Object[] h; int maxS; java.util.Comparator c; public void Heap(int, java.util.Comparator); public Object findMax();
  • 107. public Object removeMax(); public void insert(Object); public int size(); private void siftUp(int); private void siftDown(int); } Heap.javaHeap.javaimport java.lang.reflect.Array; import java.util.Comparator; import java.util.NoSuchElementException; publicclassHeap<E>{ int s; Object[] h; int maxS; Comparator c; /** * Heap takes in the initial size of the heap. * @param i the integer value of the size of the heap. */ publicHeap(int i,Comparator<?super E> comparator){ c=comparator; s=0; maxS=i; h=newObject[i]; } /** * findMax returns the largest item of the heap. * If the heap is empty it will throw a noSuchElementExcepti on. * @return E the max object */
  • 108. public E findMax(){ if(s==0){ System.out.println("an error has been thrown because the heap i s empty"); thrownewNoSuchElementException(); } return(E) h[0]; } /** * removeMax removes the largest item. If the list is empty a NoSuchElementException is thrown. * @return the max object */ public E removeMax(){ if(s==0){ System.out.println("an error has been thrown because the heap i s empty"); thrownewNoSuchElementException(); } E last =(E) h[s-1]; E first =(E) h[0]; h[0]=last; h[s-1]=null; s--; siftDown(0); return first; } /** * insert inserts an item into the heap and bubbles it into the correct position. * @param item that is inserted */ publicvoid insert(E item){ if(s==maxS-1){ maxS=maxS*2;
  • 109. Object[] grownArray =newObject[maxS]; System.arraycopy(h,0, grownArray,0, h.length); h=grownArray; } h[s]=item; siftUp(s); s++; } /** * size returns the size of the heap. * @return the integer size of the heap */ publicint size(){ return s; } /** * siftUp, sifts the node at index i up through the heap into th e correct position. * @param i the value to begin sifting */ privatevoid siftUp(int i) { int n=i; boolean inPlace =false; if(n==0){ inPlace=true; } while(inPlace==false){ int a=(n-1)/2; E below=(E) h[n]; E above=(E) h[a]; if(c.compare(below,above)>0){
  • 110. h[n]= above; h[a]=below; n=a; }else{ inPlace=true; } } } /** * SiftDown sifts the node at index i down to the correct spot in the heap. * @param i the value to begin sifting */ privatevoid siftDown(int i) { int n=i; boolean inPlace =false; while(inPlace==false){ int a=(n*2)+1; E above=(E) h[n]; E belowL=(E) h[a]; E belowR=(E) h[a+1]; if(belowL==null&& belowR==null){ return; } //if neither of the children are null if(belowL !=null&& belowR !=null){ //compare to the left child if(c.compare(above,belowL)<0&& c.compare(belowL,belowR)> =0){ System.out.println("down and to the left!"); h[a]= above;
  • 111. h[n]=belowL; n=a; //compare to the right child }elseif(c.compare(above,belowR)<0){ System.out.println("down and to the right!"); h[a+1]= above; h[n]=belowR; n=a; //otherwise its in place }else{ System.out.println("its down in place"); inPlace=true; } //if the left child isnt null }elseif(belowL !=null){ if(c.compare(above, belowL)<0){ h[n]= above; h[a]=belowL; n=a; }else{ inPlace=true; } }else{ // if the right child isnt null compare it to the parent if(c.compare(above,belowR)<0){ h[a+1]= above; h[n]=belowR; n=a; }else{ inPlace=true; }
  • 112. } } } /** * MaxHeapComparator compares two values and prioritizes t he max value. * @author tai-lanhirabayashi * * @param <E> the comparable object */ publicstaticclassMaxHeapComparator<E extendsComparable<E >>implementsComparator<E>{ @Override publicint compare(E o1, E o2){ return o1.compareTo(o2); } } /** * MinHeapComparator compares two values and prioritizes t he lower value * @author tai-lanhirabayashi * * @param <E> the comparable object */ publicstaticclassMinHeapComparator<E extendsComparable<E> >implementsComparator<E>{ @Override
  • 113. publicint compare(E o1, E o2){ return(-1* o1.compareTo(o2)); } } } PriorityQueueTest.classpublicsynchronizedclass PriorityQueueTest { PriorityQueue p; public void PriorityQueueTest(); public void start(); public void testPeek(); public void testRemove(); public void testSize(); public void testEmpty(); } PriorityQueueTest.javaPriorityQueueTest.javaimportstatic org.j unit.Assert.*; import java.util.Comparator; import org.junit.Before; import org.junit.Test; publicclassPriorityQueueTest{ PriorityQueue p; /** * Start initialized the program, with a queue of 1,2,3,4 and a max priority.
  • 114. */ @Before publicvoid start(){ Comparator<Integer> c =newHeap.MaxHeapComparator(); p=newPriorityQueue(10, c); p.add(1); p.add(2); p.add(3); p.add(4); } /** * testPeek tests the peek function. */ @Test publicvoid testPeek(){ assertEquals(4, p.peek()); p.remove(); assertEquals(3, p.peek()); p.remove(); assertEquals(2, p.peek()); p.remove(); assertEquals(1, p.peek()); p.remove(); assertEquals(null, p.peek()); } /** * restRemove tests the remove function. */ @Test publicvoid testRemove(){ assertEquals(4, p.remove()); assertEquals(3, p.remove());
  • 115. assertEquals(2, p.remove()); assertEquals(1, p.remove()); assertEquals(null, p.remove()); } /** * testSize tests the size function. */ @Test publicvoid testSize(){ assertEquals(4, p.size()); p.remove(); assertEquals(3, p.size()); p.remove(); assertEquals(2, p.size()); p.remove(); assertEquals(1, p.size()); p.remove(); assertEquals(0, p.size()); p.add(9); assertEquals(1, p.size()); } /** * testEmpty tests the isEmpty function of priorityQueue. */ @Test publicvoid testEmpty(){ assertFalse(p.isEmpty()); p.remove(); assertFalse(p.isEmpty()); p.remove(); assertFalse(p.isEmpty()); p.remove(); assertFalse(p.isEmpty());
  • 116. p.remove(); assertTrue(p.isEmpty()); p.add(5); assertFalse(p.isEmpty()); } } BSTMap.classpublicsynchronizedclass BSTMap extends Map { nObject obj; BSTMap left; BSTMap right; int s; BSTMap parent; public void BSTMap(Object, Object); public void setParent(BSTMap); public BSTMap getParent(); public void setLeft(BSTMap); public void setRight(BSTMap); public BSTMap getLeft(); public BSTMap getRight(); boolean isLeaf(); } BSTMap.javaBSTMap.java publicclassBSTMap<K,V>extendsMap{ nObject obj; BSTMap<K,V> left; BSTMap<K,V> right; int s; BSTMap<K,V> parent; /** * BSTMap creates a node with a K key and V value.
  • 117. * @param ke the K value * @param va the V value */ publicBSTMap(K ke, V va){ obj=new nObject(ke,va); left=null; right=null; parent=null; } /** * setParent sets the BSTMap which is this nodes parent. * @param p the parent */ publicvoid setParent(BSTMap<K,V> p){ parent=p; } /** * getParent returns the parent of this node. * @return BSTMap that is this nodes parent. */ publicBSTMap<K,V> getParent(){ return parent; } /** * setLeft sets the BSTMap left child. * * @param child BSTMap that is this nodes child. */ publicvoid setLeft(BSTMap<K,V> child){ left=child; if(child!=null){ left.setParent(this); }
  • 118. } /** * setRight sets the this nodes BSTMap child. * @param child BSTMap that is this nodes child. */ publicvoid setRight(BSTMap<K,V> child){ right=child; if(child!=null){ right.setParent(this); } } /** * getLeft returns this nodes left BSTMap child. * @return BSTMap this nodes left child */ publicBSTMap<K,V> getLeft(){ return left; } /** * getRight returns this nodes right BSTMap child. * @return BSTMap this nodes right child */ publicBSTMap<K,V> getRight(){ return right; } /** * isLeaf checks if the node is a leaf node by checking if it ha s children. * * It returns true for leaf, false for if it has children. * @return boolean if the node is a leaf node. */ boolean isLeaf(){
  • 119. if(getLeft()==null&& getRight()==null){ returntrue; } returnfalse; } } BinaryTreeTest.classpublicsynchronizedclass BinaryTreeTest { BinaryTree t; public void BinaryTreeTest(); public void before(); public void testSetup(); public void testGetLeft(); public void testGetRight(); public void isLeaf(); public void setLeft(); public void setRight(); public void setValue(); } BinaryTreeTest.javaBinaryTreeTest.javaimportstatic org.junit.A ssert.*; import org.junit.Before; import org.junit.Test; /** * BinaryTreeTest tests to see if Binary Tree functions as expect ed. * @author tai-lanhirabayashi * */ publicclassBinaryTreeTest{
  • 120. BinaryTree t; /** * before sets up a base case. */ @Before publicvoid before(){ t=newBinaryTree(null,"head",null); t.setLeftChild(newBinaryTree(null,"second",null)); t.getLeftChild().setLeftChild(newBinaryTree(null,"third", null)); } /** * testSetup makes sure the test has been initialized. */ @Test publicvoid testSetup(){ assertEquals(t.getValue(),"head"); } /** * tests the getLeft function */ @Test publicvoid testGetLeft(){ assertEquals(t.getLeftChild().getValue(),"second"); } /** * Tests the get right function */ @Test publicvoid testGetRight(){ assertEquals(t.getRightChild(),null); }
  • 121. /** * Tests the isLeaf function. */ @Test publicvoid isLeaf(){ assertEquals(t.getLeftChild().getLeftChild().isLeaf(),true); } /** * Tests the setLeft function */ @SuppressWarnings("unchecked") @Test publicvoid setLeft(){ t.setLeftChild(newBinaryTree(null,"replace",null)); assertEquals(t.getLeftChild().getValue(),"replace"); } /** * tests the setRightChild function */ @SuppressWarnings("unchecked") @Test publicvoid setRight(){ t.setRightChild(newBinaryTree(null,"right",null)); assertEquals(t.getRightChild().getValue(),"right"); } /** * Tests the setValue function. */ @Test publicvoid setValue(){ t.getLeftChild().setValue("reset"); assertEquals(t.getLeftChild().getValue(),"reset"); }
  • 122. } ArithmeticExpressionTest.classpublicsynchronizedclass ArithmeticExpressionTest { ArithmeticExpression a; public void ArithmeticExpressionTest(); public void startUp() throws java.text.ParseException; public void testExceptions(); public void testToString(); public void testEval(); public void testVar() throws java.rmi.NotBoundException, java.text.ParseException; public void testPostFix(); public void testWithoutSpaces() throws java.text.ParseException; } ArithmeticExpressionTest.javaArithmeticExpressionTest.javaim portstatic org.junit.Assert.*; import java.rmi.NotBoundException; import java.text.ParseException; import org.junit.Before; import org.junit.Test; /** * ArithmeticExpressionTest tests the functionality of Arithmeti cExpression. *** Note, the Program includes postFix() which returns a postfi x String of the equation. *** It can also handle strings with or without spaces. * *
  • 123. * @author tai-lan hirabayashi * */ publicclassArithmeticExpressionTest{ ArithmeticExpression a; /** * StartUp sets up the base case scenario. * @throws ParseException if the equation is not valid. */ @Before publicvoid startUp()throwsParseException{ a=newArithmeticExpression("3 + 4 * 2"); } /** * testExceptions tests the programs thrown exceptions. */ @Test publicvoid testExceptions(){ boolean errorThrown =false; try{ a=newArithmeticExpression("3 + * 2"); }catch(ParseException e){ errorThrown=true; } assert(errorThrown); errorThrown=false; try{ a.setVariable("y",2); }catch(NotBoundException e){ errorThrown=true; } assert(errorThrown);
  • 124. } /** * testToString tests the toString method of the ArithmeticEx pression */ @Test publicvoid testToString(){ System.out.println("this is toString: "+ a.toString(a.t)); assertEquals(a.toString(a.t),"((2*4)+3)"); } /** * testEval tests the evaluate method of ArithmeticExpression */ @Test publicvoid testEval(){ assertEquals(a.evaluate(a.t),11); } /** * testVar tests the setVariable function of ArithmeticExpress ion * by checking how a variable is handled. * @throws NotBoundException * @throws ParseException if the equation is not valid. */ @Test publicvoid testVar()throwsNotBoundException,ParseException{ a=newArithmeticExpression("2 + 3 * x"); assertEquals(a.evaluate(a.t),2); a.setVariable("x",2); assertEquals(a.evaluate(a.t),8); } /** * Tests the postFix() method. */ @Test publicvoid testPostFix(){
  • 125. assertEquals(a.toPostfixString(a.t),"3 4 2 * +"); } @Test publicvoid testWithoutSpaces()throwsParseException{ a=newArithmeticExpression("2+3*x"); assertEquals(a.evaluate(a.t),2); } } nObject.classpublicsynchronizedclass nObject { Object key; Object value; public void nObject(Object, Object); public Object getKey(); public Object getValue(); public void changeKey(Object); public void changeValue(Object); } nObject.javanObject.java publicclass nObject<K,V>{ K key; V value; /** * nObject creates a new nObject object with a K,V values he ld. * @param ky the K key value * @param val the V value value. */ public nObject (K ky, V val){ key=ky; value=val; }
  • 126. /** * getKey returns the K key. * @return K, the key */ public K getKey(){ return key; } /** * getValue returns the V value. * @return V value */ public V getValue(){ return value; } /** * changeK allows the user to pass in a new K key. * @param ky K to be changed to. */ publicvoid changeKey(K ky){ key=ky; } /** * changeValue allows the value to be changed. * @param val the new V value. */ publicvoid changeValue(V val){ value=val; } }
  • 127. BSTMapTest.classpublicsynchronizedclass BSTMapTest { BSTMap m; public void BSTMapTest(); public void startUp(); public void testGetLeft(); public void testGetRight(); public void testGetParent(); public void testIsLeaf(); public void testSetLeft(); public void testSetRight(); public void testSetParent(); } BSTMapTest.javaBSTMapTest.javaimportstatic org.junit.Assert .*; import org.junit.Before; import org.junit.Test; publicclassBSTMapTest{ BSTMap m; /** * startUp creates a new instance of BSTMap. */ @Before publicvoid startUp(){ m=newBSTMap(1,"one"); } /** * testGetLeft tests getLeft(). *
  • 128. * It tests when it doesnt exist, when it does exist, when it ha s been changed, and when it has been removed. */ @Test publicvoid testGetLeft(){ assertEquals(null, m.getLeft()); m.setRight(newBSTMap(3,"three")); assertEquals(null, m.getLeft()); BSTMap child=newBSTMap(2,"two"); BSTMap a=newBSTMap(1,"a"); m.setLeft(child); assertEquals(child, m.getLeft()); m.setLeft(a); assertEquals(a, m.getLeft()); m.setLeft(null); assertEquals(null, m.getLeft()); } /** * testGetRight tests getRight(). * * It tests when it doesnt exist, when it does exist, and when i t has been removed. */ @Test publicvoid testGetRight(){ assertEquals(null, m.getRight()); m.setLeft(newBSTMap(2,"two")); assertEquals(null, m.getRight()); BSTMap child =newBSTMap(3,"three"); BSTMap a=newBSTMap(1,"a"); m.setRight(child); assertEquals(child, m.getRight()); m.setRight(a); assertEquals(a, m.getRight());
  • 129. m.setRight(null); assertEquals(null, m.getRight()); } /** * testGetParent tests getParent() * * It tests when there is a parent, when there is not a parent. */ @Test publicvoid testGetParent(){ assertEquals(null, m.getParent()); m.setLeft(newBSTMap(2,"two")); assertEquals(null, m.getParent()); BSTMap child =newBSTMap(3,"three"); m.setRight(child); assertEquals(m, child.getParent()); } /** * testIsLeaf tests to see if a node is a leaf. * * It tests when it has no children, when it has a left child, a right child, both, and when they have been removed. */ @Test publicvoid testIsLeaf(){ assertTrue(m.isLeaf()); m.setLeft(newBSTMap(2,"two"));
  • 130. assertFalse(m.isLeaf()); m.setRight(newBSTMap(3,"three")); assertFalse(m.isLeaf()); m.setLeft(null); assertFalse(m.isLeaf()); m.setRight(null); assertTrue(m.isLeaf()); } /** * testSetLeft tests setLeft() * */ @Test publicvoid testSetLeft(){ assertEquals(null, m.getLeft()); BSTMap child=newBSTMap(2,"two"); m.setLeft(child); m.setRight(newBSTMap(3,"three")); assertEquals(child,m.getLeft()); m.setLeft(null); assertEquals(null,m.getLeft()); } /** * testSetRight tests setRight */ @Test publicvoid testSetRight(){ BSTMap child=newBSTMap(2,"two"); BSTMap a=newBSTMap(1,"a"); assertEquals(null, a.getRight()); a.setRight(child);
  • 131. assertEquals(child, a.getRight()); a.setRight(null); assertEquals(null, a.getRight()); } /** * testSetParent tests setParent */ @Test publicvoid testSetParent(){ BSTMap child=newBSTMap(2,"two"); BSTMap a=newBSTMap(1,"a"); assertEquals(null, a.getParent()); a.setParent(child); assertEquals(child, a.getParent()); a.setParent(null); assertEquals(null, a.getParent()); } } HTree.classpublicsynchronizedclass HTree { private String s; private int f; HTree l; HTree r; public void HTree(int, String); public void setL(HTree); public void setR(HTree); public HTree getL(); public HTree getR(); public String getS(); public int getF(); public boolean isLeaf();
  • 132. public int getBelow(); } HTree.javaHTree.java publicclassHTree<E extendsComparable<E>>{ privateString s; privateint f; HTree l; HTree r; /** * HTree creates a HTree object containing a int frequency an d a String str. * @param frequency the integer frequency of the str * @param str the str value of this HTree */ publicHTree(int frequency,String str){ s=str; f=frequency; l=null; r=null; } /** * setL sets the left HTree value * @param left the HTree that is the left child of this node */ publicvoid setL(HTree left){ l=left; } /** * setR sets the right HTree child value * @param right the HTree that is the right child of this node */
  • 133. publicvoid setR(HTree right){ r=right; } /** * getL returns the left child of this node. * @return HTree the left child. */ publicHTree getL(){ return l; } /** * getR returns the right child of this node. * @return HTree the right child. */ publicHTree getR(){ return r; } /** * getS returns the string value associated with this node * @return String the value of this node */ publicString getS(){ return s; } /** * getF returns the frequency value associated with this node. * @return the int frequency value associated with this node. */ publicint getF(){ return f; }
  • 134. /** * isLeaf returns boolean if this node is a leaf. * @return boolean wether this node is a leaf. */ publicboolean isLeaf(){ if(l==null&&r==null){ returntrue; } returnfalse; } /** * getBelow recursively finds how many children this node h as. * * **this does not handle trees with only one child (as this do es not occur in a huffmanTree) * @return the int number height */ publicint getBelow(){ if(isLeaf()){ return0; }else{ int a=1+l.getBelow(); int b=1+r.getBelow(); if(a>b){ System.out.println("returning a: "+ a); return a; } System.out.println("returning b"+ b); return b; } }
  • 135. } HeapTest.classpublicsynchronizedclass HeapTest { Heap h; Heap min; public void HeapTest(); public void start(); public void testFindMax(); public void testRemoveMax(); public void testSize(); public void testMin(); } HeapTest.javaHeapTest.javaimportstatic org.junit.Assert.*; import java.util.Comparator; import org.junit.Before; import org.junit.Test; publicclassHeapTest{ Heap h; Heap min; /** * start creates a test case of heap both min and max compara tor. */ @Before publicvoid start(){ Comparator<Integer> c =newHeap.MaxHeapComparator<Intege r>();
  • 136. Comparator<Integer> m =newHeap.MinHeapComparator<Intege r>(); min=newHeap(10,m); min.insert(1); min.insert(2); min.insert(3); min.insert(4); h=newHeap(10,c); System.out.println("this is 1"); h.insert(1); System.out.println(h.h[0]); System.out.println("this is 2"); h.insert(2); System.out.println(h.h[0]+","+h.h[1]); System.out.println("this is 3"); h.insert(3); System.out.println(h.h[0]+","+h.h[1]+","+h.h[2]); System.out.println("this is 4"); h.insert(4); System.out.println(h.h[0]+","+h.h[1]+","+h.h[2]+","+h.h[3]); } /** * testFindMax tests the findMax function */ @Test publicvoid testFindMax(){ assertEquals(4, h.findMax()); assertEquals(4, h.removeMax()); assertEquals(3, h.findMax()); assertEquals(1, min.findMax()); assertEquals(1, min.removeMax()); assertEquals(2, min.findMax());
  • 137. } /** * testRemoveMax tests the remove max function */ @Test publicvoid testRemoveMax(){ assertEquals(4, h.findMax()); assertEquals(4,h.removeMax()); assertEquals(3, h.findMax()); assertEquals(3,h.removeMax()); assertEquals(2,h.removeMax()); assertEquals(1,h.removeMax()); assertEquals(0,h.size()); assertEquals(1, min.findMax()); } /** * testSize tests the size function of heap. */ @Test publicvoid testSize(){ assertEquals(4, h.size()); int o=(Integer) h.removeMax(); assertEquals(3, h.size()); h.insert(o); assertEquals(4, h.size()); h.removeMax(); h.removeMax(); h.removeMax(); h.removeMax(); assertEquals(0, h.size()); assertEquals(4, min.size());
  • 138. } /** * testMin tests the minSort comparator. */ @Test publicvoid testMin(){ assertEquals(4, min.size()); assertEquals(1,min.removeMax()); assertEquals(2,min.removeMax()); assertEquals(3,min.removeMax()); assertEquals(4,min.removeMax()); } } HuffmanTree$CountPair.classsynchronizedclass HuffmanTree$CountPair { int _count; String _text; private void HuffmanTree$CountPair(HuffmanTree, String, int); } HuffmanTree$CountPairTreeComparator.classsynchronizedclass HuffmanTree$CountPairTreeComparator implements java.util.Comparator { private void HuffmanTree$CountPairTreeComparator(HuffmanTree); public int compare(BinaryTree, BinaryTree);
  • 139. } HuffmanTree.classpublicsynchronizedclass HuffmanTree { java.io.File current; BSTMap _lookupTable; BinaryTree _huffmanTree; public void HuffmanTree(); publicstatic HuffmanTree newTreeFromFile(java.io.File) throws java.io.FileNotFoundException; publicstatic HuffmanTree newTreeFromCompressedFile(java.io.File) throws java.io.FileNotFoundException; private void buildFromFile(java.io.File) throws java.io.FileNotFoundException; private void buildTreeFromMap(PriorityQueue); private void buildFromCompressedFile(java.io.File) throws java.io.FileNotFoundException; public void saveCompressedFile(java.io.File); public void saveExpandedFile(java.io.File); public String encode(String); public String decode(String); } HuffmanTree.javaHuffmanTree.javaimport java.io.File; import java.io.FileNotFoundException; import java.util.Comparator; import java.util.Scanner; import java.util.Set; /** * This class implements the basic functionality of Huffman co mpression and expansion. *
  • 140. * @author C. Andrews * */ publicclassHuffmanTree{ File current; BSTMap<String,String> _lookupTable =newBSTMap<String,Str ing>(null,null); BinaryTree<CountPair> _huffmanTree; /** * This is a factory method for reading in a fresh text file to i nitialize the Huffman tree. * * @param file the document to use for the code frequencies * @return a HuffmanTree containing the Huffman codes bas ed on the frequencies observed in the document * @throws FileNotFoundException */ publicstaticHuffmanTree newTreeFromFile(File file)throwsFile NotFoundException{ HuffmanTree tree =newHuffmanTree(); tree.buildFromFile(file); return tree; } /** * This is a factory method that builds a new HuffmanTree fr om a compressed file. * * @param file a file that has been compressed with a Huffma n tool * @return a new HuffmanTree containing the codes for deco ding the file * @throws FileNotFoundException */
  • 141. publicstaticHuffmanTree newTreeFromCompressedFile(File file )throwsFileNotFoundException{ // TODO implement this } /** * This method builds the Huffman tree from the input file. * * @param file the file to use to construct the Huffman tree * @throws FileNotFoundException */ privatevoid buildFromFile(File file)throwsFileNotFoundExcepti on{ current=file; // read file and build the map of the character frequencies Map<String,Integer> freqMap =newBSTMap<String,Integer>(); Scanner scanner =newScanner(file); scanner.useDelimiter(""); String character; while(scanner.hasNext()){ character = scanner.next(); Integer count = freqMap.get(character); if(count ==null){ count =Integer.valueOf(0); } freqMap.put(character, count+1); } // for each key, make a tree and load it into the priority queue
  • 142. PriorityQueue<BinaryTree<CountPair>> treeQueue =newPriorit yQueue<BinaryTree<CountPair>>(freqMap.keySet().size(),new CountPairTreeComparator()); BinaryTree<CountPair> tmpTree; for(String key: freqMap.keySet()){ int frequency = freqMap.get(key); tmpTree =newBinaryTree<CountPair>(null,newCountPa ir(key, frequency),null); treeQueue.add(tmpTree); } // while the size of the priority queue is greater than 1, combine the top items into a tree and put them back in the priority queue BinaryTree<CountPair> tree1, tree2; int newFrequency; String newText; while(treeQueue.size()>1){ tree1 = treeQueue.remove(); tree2 = treeQueue.remove(); // If the height of the second tree is less than the height of the fi rst, // or the heights are the same and tree2 precedes tree1 alphabeti cally, swap them so // the smaller/earlier tree is put on the left if(tree1.getValue()._text.length()> tree2.getValue()._text.length () ||( tree1.getValue()._text.length()== tree2.getValue()._text.lengt h() && tree1.getValue()._text.compareTo(tree2.getValue()._text)>0 )){ tmpTree = tree1; tree1 = tree2; tree2 = tmpTree; }
  • 143. // create a new tree combining the two smaller trees, computing a new frequency that is the sum of the // children frequencies and a new text that is the appended comb ination of the children's text newFrequency = tree1.getValue()._count + tree2.getVal ue()._count; newText = tree1.getValue()._text + tree2.getValue()._te xt; tmpTree =newBinaryTree<CountPair>(tree1,newCountP air(newText, newFrequency), tree2); treeQueue.add(tmpTree); } // pull the completed tree from the priority queue BinaryTree<CountPair> tree = treeQueue.remove(); // create map of symbols to code lengths using the tree Map<String,Integer> codeLengthMap =newMap<String,Integer> (); // TODO implement this part PriorityQueue pq=newPriorityQueue(setC.size(),new treeCompa rator()); buildTreeFromMap(pq); } privatevoid buildTreeFromMap(PriorityQueue q){ // TODO Auto-generated method stub } /**
  • 144. * Builds the tree using information found in a compressed fil e. * * The table is the first thing we find in the file. The first pie ce of data is the length * of the table (L). This is followed by L pairs of character an d code length pairs. * * @param file the file to read the Huffman code from. */ privatevoid buildFromCompressedFile(File file)throwsFileNotF oundException{ // TODO implement this } /** * Read the original file and compress it using the Huffman cod es, writing the result * into the output file. * * @param outputFile the output file */ publicvoid saveCompressedFile(File outputFile){ // TODO implement this } /** * Read the compressed file that initialized this object and wr ite the decoded version out * into the output file. * * @param outputFile the destination file for the uncompress ed file.
  • 145. */ publicvoid saveExpandedFile(File outputFile){ // TODO implement this } /** * This method reads in a String of text and returns a String o f 0s and 1s corresponding to the Huffman code stored in this tre e. * @param text the text to be encoded * @return a String representation of the Huffman code */ publicString encode(String text){ StringBuilder builder =newStringBuilder(); String tmp; for(int i =0; i < text.length(); i++){ tmp = _lookupTable.get(String.valueOf(text.charAt(i))); builder.append(tmp); } return builder.toString(); } /** * This method reads in a String representation of a Huffman code corresponding to this Huffman tree and decodes it. * @param text a String representation of the a Huffman code d message * @return the original text */ publicString decode(String text){ StringBuilder builder =newStringBuilder(); BinaryTree<CountPair> current = _huffmanTree;
  • 146. for(int i =0; i < text.length(); i++){ char c = text.charAt(i); if(c =='0'){ current = current.getLeftChild(); }elseif(c =='1'){ current = current.getRightChild(); }else{ thrownewRuntimeException("Encountered unexpected character in coded String"); } if(current.isLeaf()){ builder.append(current.getValue()._text); current = _huffmanTree; } } return builder.toString(); } privateclassCountPair{ int _count; String _text; privateCountPair(String text,int count){ _text = text; _count = count; } } privateclassCountPairTreeComparatorimplementsComparator<B inaryTree<CountPair>>{
  • 147. @Override publicint compare(BinaryTree<CountPair> t1,BinaryTree<Coun tPair> t2){ CountPair p1 = t1.getValue(); CountPair p2 = t2.getValue(); if(p1._count != p2._count){ return p2._count - p1._count; }elseif(p1._text.length()!= p2._text.length()){ return-p1._text.length()- p2._text.length(); }else{ return p1._text.compareTo(p2._text); } } } } nObjectTest.classpublicsynchronizedclass nObjectTest { nObject o; public void nObjectTest(); public void setUp(); public void testChangeKey(); public void testChangeValue(); public void testGetKey(); public void testGetValue(); } nObjectTest.javanObjectTest.javaimportstatic org.junit.Assert.*
  • 148. ; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; publicclass nObjectTest { nObject o; /** * setUp sets up the test. */ @Before publicvoid setUp(){ o=new nObject("one",1); } /** * tests the change Key function */ @Test publicvoid testChangeKey(){ assertEquals("one", o.getKey()); o.changeKey("two"); assertEquals("two", o.getKey()); } /** * tests the change Value function */ @Test publicvoid testChangeValue(){ assertEquals(1, o.getValue()); o.changeValue(2); assertEquals(2, o.getValue()); }
  • 149. /** * testGetKey tests the getKey method */ @Test publicvoid testGetKey(){ assertEquals("one", o.getKey()); o.changeKey("two"); assertEquals("two", o.getKey()); } /** * testGetValue tests get Value */ @Test publicvoid testGetValue(){ assertEquals(1, o.getValue()); o.changeValue(2); assertEquals(2, o.getValue()); } } MapTest.classpublicsynchronizedclass MapTest { Map m; public void MapTest(); public void start(); public void testContainsKey(); public void testGet(); public void testKeySet(); public void testPut(); public void testRemove(); }
  • 150. MapTest.javaMapTest.javaimportstatic org.junit.Assert.*; import org.junit.Before; import org.junit.Test; publicclassMapTest{ Map m; /** * start() creates an initial map to test. */ @Before publicvoid start(){ m=newMap(); } /** * testContainsKey tests the containsKey function. * It tests when there are more than one object, one object, * when the object is contained, and when the object is not co ntained. */ @Test publicvoid testContainsKey(){ assertFalse(m.containsKey(5)); m.put(5,"five"); m.put(4,"four"); assertTrue( m.containsKey(5)); m.remove(5); assertFalse(m.containsKey(5)); m.remove(4); assertFalse(m.containsKey(4));
  • 151. } /** * testGet tests the get function of map. * * It tests when there are no objects, when there is an object, and when there are more than one objects. */ @Test publicvoid testGet(){ assertEquals(null, m.get(5)); m.put(5,"five"); assertEquals("five",m.get(5)); m.put(4,"four"); assertEquals("five",m.get(5)); } /** * testKeySet tests keySet. */ @Test publicvoid testKeySet(){ assertEquals(true, m.keySet().isEmpty()); m.put(5,"five"); assertEquals(false, m.keySet().isEmpty()); assertEquals(true, m.keySet().contains(5)); } /** * testPut tests the put method of map. */ @Test publicvoid testPut(){ assertEquals(null, m.get(5));
  • 152. m.put(5,"five"); assertEquals("five",m.get(5)); m.put(5,"changed"); m.put(6,"six"); assertEquals("changed",m.get(5)); assertEquals("six",m.get(6)); } /** * testRemove tests map's remove function * * It tests if it can remove something that isnt in map, and re moval of objects not in order. */ @Test publicvoid testRemove(){ assertEquals(null, m.remove("a")); m.put(5,"five"); m.put(4,"four"); m.put(3,"three"); assertEquals("three", m.remove(3)); assertEquals("five", m.remove(5)); assertEquals("four", m.remove(4)); } } .project assignment 8
  • 153. org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature 1/1/13 10:10 PMCS 211 Homework Seven — Fall 2012 Page 1 of 3http://web.cs.mtholyoke.edu/~candrews/cs211/homework/hw7. html CS 212 — Homework Seven Huffman Codes Due: 13 November 2012, 11:59p Worth: 90 points The Task This week you are going to implement a new data structure and the main Huffman tree. Next week we will finish this off with a full application for compressing and decompressing text files.
  • 154. Part one: PriorityQueue [20 pts] As I said in class, I redesigned final product of this project, so we need to redo the PriorityQueue and the Heap. This is actually good practice for you because refactoring code to meet changing specifications is a common occurrence in software development. We basically want to have a different level of control, so we are going to change our classes to be closer to the PriorityQueue provided in the Java API. The new interface for PriorityQueue looks like this: public PriorityQueue(int initialCapacity,Comparator<? super E> comparator) This is the constructor. It should initialize the heap using the initialCapacity. The comparator is the tool that will allow us to change how priority is calculated for various inputs. public E peek() This returns the next item without removing it. This returns null if the queue is empty. E remove() This removes the first item from the queue. void add(E item) This adds item to the queue boolean isEmpty() Obviously, this says if the queue is empty or not. int size() This should return the size of the queue. The main difference is the addition of the Comparator. Comparators are classes that provide the same
  • 155. functionality as compareTo(). You will use this instead of the compareTo method for comparing items in the queue. We can write different comparators to give us high value priority, low value priority, or more complex variations (which is why we need to do this). Doing this will mean that the wrapper class you wrote for the last assignment is no longer needed, the priority will be supplied in a different way. You may be wondering about the Comparator<? super E>. We are specifying that our Comparator is capable of comparing two objects of type E. The ? says that it can compare two Es, or E is a subclass of the class that the Comparator can handle. You will, of course, need to adjust the Heap as well to work with this new PriorityQueue. Add the Comparator to the constructor and update siftup and siftdown to use it. Also, write two static, public inner classes on the Heap called MaxHeapComparator and MinHeapComparator. These comparators will provide the normal functionality of min and max by calling the compareTo methods on the stored items (i.e., they will only work for objects that implement Comparable. Part two: Map [30 pts] Next, we need a new data structure. We are going to build this in two pieces so that we can reuse the http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.ht ml 1/1/13 10:10 PMCS 211 Homework Seven — Fall 2012
  • 156. Page 2 of 3http://web.cs.mtholyoke.edu/~candrews/cs211/homework/hw7. html interface later. So, the first this you should build is an interface called Map<K extends Comparable<K>,V>. The interface should look like this: void put(K key, V value) This should load the value value into the map at the location associated with the key, replacing any preexisting value already associated with the key. V get(K key) This should fetch the value V associated with the key key, or null, if no match can be found. boolean containsKey(K key) This will report if there is a value associated with the value key in the map. V remove(K key) This method should remove the entry associated with key and return the associated value. Return null if the key is not found. Set<K> keySet() This method should return a Set of all available keys in the map. You may use the java.util.TreeSet class to return these. You can build these on the fly using a traversal, or collect them as new keys are added to the map. Of course, since this is just the interface, you will need to implement an actual instance so that you can use it. This instance should be called BSTMap<K,V>. Obviously, this will use a binary search tree to actually
  • 157. implement the methods described above. While one perfectly valid implementation choice would be to create a separate binary search tree class and just use it to implement the described methods, it can force you to jump through some hoops to make methods like get and containsKey to work properly. So instead, you can build the binary search tree structure directly into your implementation of BSTMap. When constructing the underlying BST, you will need to create some form of node structure that will hold both the key and the value. You will, of course, need to adjust the pseudocode that we walked through in class to work directly with the key values. It is important that these nodes are not visible outside of the class. The other major aspect of this design is whether you use an array or links in the nodes to implement the actual tree. I encourage you to use the linked version as we will be building on this class later and will want it to be easy to move nodes around. Part three: The Huffman tree [40 pts] Once you have built your map, you will have enough tools to actually build the Huffman tree. The tree should be in a class called HuffmanTree. The interface should look like this: static HuffmanTree newTreeFromFile(File file) This is a static factory method that creates a new Huffman tree. In essence, this just creates the new object and calls buildFromFile on it. This should throw a FileNotFoundException when appropriate. private void buildFromFile(File file) This reads in an unencoded file and builds the Huffman tree
  • 158. based on the character frequencies. This should throw a FileNotFoundException when appropriate. String encode(String text) This method takes in some plain text and returns the encoded version as a String of 1's and 0's. String decode(String text) This method takes in a String of 1's and 0's and returns a decoded raw text version. For this assignment I am introducing you to a new Java design pattern called the "factory method". Factory methods are methods (usually static) that return new instances of a class. We typically use them when there is some complex initialization that needs to be performed or we have more than one way in which we want an object to be created. In this case, we are paving the way for future development. The factory method should just create a new HuffmanTree and then call buildFromFile on it. To actually build the tree, you should start by reading the seed file one character at a time, using the Map to keep track of the frequencies of each character. Once the file has been consumed, you will use your PriorityQueue to to build the Huffman tree. You will want to create a private inner node class that holds a frequency and a String. Since we want to assemble everything into a binary tree structure (it will be a heap, but we won't use the Heap class for it), also include left and right children. Call this class HTree. Write a constructor that sets all of the fields at
  • 159. 1/1/13 10:10 PMCS 211 Homework Seven — Fall 2012 Page 3 of 3http://web.cs.mtholyoke.edu/~candrews/cs211/homework/hw7. html once. For each character you read in, create an HTree wrapper for it and its frequency and put it in the PriorityQueue. The general algorithm for building the Huffman tree goes like this: Remove the two trees with the lowest frequency from the queue Use these two trees as the left and right children of a new tree with a root node that has the frequency of the two children combined. Return this tree to the queue Repeat until there is only one tree — this is the Huffman tree To make this work, you will want to write a Comparator that uses the lowest frequency as the highest priority. Unfortunately, this algorithm does not create unique trees. We would like to build a canonical Huffman tree. In order to do that, we will add some more rules. When we have two trees that have the same frequency, we will take the shorter one first. When we have two trees of the same complexity and the same length, we will use alphabetical order to determine priority (e.g., 'a' comes before 'b'). In addition, when we build our subtrees, the shorter tree goes on the left. If the trees are the same length, the first alphabetically goes of the left (note that this is true regardless of frequency).
  • 160. Once the tree is fully constructed, you should create a second map that stores the final codes for each character. The tree and this map should be the two data structures that you keep around after the construction process. For encoding, you will use the map to lookup each character, and for decoding, you will use the tree to find the decoded characters. I want you to notice that the two methods, encode and decode are really only for testing. They transform the data into Strings of 1s and 0s, which is certainly not a compressed form for the data. Turning the assignment in... Commented source files and tests should be put into a single directory, zipped, tarred or jarred, and submitted online into your course dropbox on ella (I only want source files, I do not want any class files). Please name your files cs211_pid_hw7.suffix, where pid is your Mount Holyoke email account name and suffix is the appropriate suffix for your archive format. Last modified: Mon Dec 17 17:11:21 EST 2012 1/1/13 10:08 PM Page 1 of 3http://web.cs.mtholyoke.edu/~candrews/cs211/examples/Huffm anTree.html import java.io.File; import java.io.FileNotFoundException;
  • 161. import java.util.Comparator; import java.util.Scanner; import java.util.Set; /** * This class implements the basic functionality of Huffman compression and expansion. * * @author C. Andrews * */ public class HuffmanTree { Map<String, String> _lookupTable = new BSTMap<String, String>(); BinaryTree<CountPair> _huffmanTree; /** * This is a factory method for reading in a fresh text file to initialize the Huffman tree. * * @param file the document to use for the code frequencies * @return a HuffmanTree containing the Huffman codes based on the frequencies observed in the document * @throws FileNotFoundException */ public static HuffmanTree newTreeFromFile(File file) throws FileNotFoundException{ HuffmanTree tree = new HuffmanTree(); tree.buildFromFile(file); return tree; } /** * This is a factory method that builds a new HuffmanTree
  • 162. from a compressed file. * * @param file a file that has been compressed with a Huffman tool * @return a new HuffmanTree containing the codes for decoding the file * @throws FileNotFoundException */ public static HuffmanTree newTreeFromCompressedFile(File file) throws FileNotFoundException{ // TODO implement this } /** * This method builds the Huffman tree from the input file. * * @param file the file to use to construct the Huffman tree * @throws FileNotFoundException */ private void buildFromFile(File file) throws FileNotFoundException { // read file and build the map of the character frequencies Map<String, Integer> freqMap = new BSTMap<String, Integer>(); Scanner scanner = new Scanner(file); scanner.useDelimiter(""); String character; while (scanner.hasNext()){ character = scanner.next(); Integer count = freqMap.get(character); if (count == null){ count = Integer.valueOf(0);
  • 163. } freqMap.put(character, count+1); } // for each key, make a tree and load it into the priority queue PriorityQueue<BinaryTree<CountPair>> treeQueue = new PriorityQueue<BinaryTree<CountPair>>(freqMap.keySet().size( ), new CountPairTreeComparator BinaryTree<CountPair> tmpTree; for (String key: freqMap.keySet()){ int frequency = freqMap.get(key); tmpTree = new BinaryTree<CountPair>(null, new CountPair(key, frequency), null); treeQueue.add(tmpTree); } // while the size of the priority queue is greater than 1, combine the top items into a tree and put them back in the priority queue BinaryTree<CountPair> tree1, tree2; int newFrequency; 1/1/13 10:08 PM Page 2 of 3http://web.cs.mtholyoke.edu/~candrews/cs211/examples/Huffm anTree.html String newText; while (treeQueue.size() > 1){
  • 164. tree1 = treeQueue.remove(); tree2 = treeQueue.remove(); // If the height of the second tree is less than the height of the first, // or the heights are the same and tree2 precedes tree1 alphabetically, swap them so // the smaller/earlier tree is put on the left if (tree1.getValue()._text.length() > tree2.getValue()._text.length() ||( tree1.getValue()._text.length() == tree2.getValue()._text.length() && tree1.getValue()._text.compareTo(tree2.getValue()._text) > 0)){ tmpTree = tree1; tree1 = tree2; tree2 = tmpTree; } // create a new tree combining the two smaller trees, computing a new frequency that is the sum of the // children frequencies and a new text that is the appended combination of the children's text newFrequency = tree1.getValue()._count + tree2.getValue()._count; newText = tree1.getValue()._text + tree2.getValue()._text; tmpTree = new BinaryTree<CountPair>(tree1, new CountPair(newText, newFrequency), tree2); treeQueue.add(tmpTree); } // pull the completed tree from the priority queue BinaryTree<CountPair> tree = treeQueue.remove(); // create map of symbols to code lengths using the tree Map<String, Integer> codeLengthMap = new Map<String, Integer>();
  • 165. // TODO implement this part buildTreeFromMap(codeLengthMap); } /** * Builds the tree using information found in a compressed file. * * The table is the first thing we find in the file. The first piece of data is the length * of the table (L). This is followed by L pairs of character and code length pairs. * * @param file the file to read the Huffman code from. */ private void buildFromCompressedFile(File file) throws FileNotFoundException{ // TODO implement this } /** * Read the original file and compress it using the Huffman codes, writing the result * into the output file. * * @param outputFile the output file */ public void saveCompressedFile(File outputFile){ // TODO implement this }
  • 166. /** * Read the compressed file that initialized this object and write the decoded version out * into the output file. * * @param outputFile the destination file for the uncompressed file. */ public void saveExpandedFile(File outputFile){ // TODO implement this } /** * This method reads in a String of text and returns a String of 0s and 1s corresponding to the Huffman code stored in this tree. * @param text the text to be encoded * @return a String representation of the Huffman code */ public String encode(String text){ StringBuilder builder = new StringBuilder(); String tmp; for (int i =0; i < text.length(); i++){ tmp = _lookupTable.get(String.valueOf(text.charAt(i))); builder.append(tmp); } 1/1/13 10:08 PM Page 3 of 3http://web.cs.mtholyoke.edu/~candrews/cs211/examples/Huffm anTree.html
  • 167. return builder.toString(); } /** * This method reads in a String representation of a Huffman code corresponding to this Huffman tree and decodes it. * @param text a String representation of the a Huffman coded message * @return the original text */ public String decode(String text){ StringBuilder builder = new StringBuilder(); BinaryTree<CountPair> current = _huffmanTree; for (int i =0; i < text.length(); i++){ char c = text.charAt(i); if (c == '0'){ current = current.getLeft(); }else if (c == '1'){ current = current.getRight(); }else{ throw new RuntimeException("Encountered unexpected character in coded String"); } if (current.isLeaf()){ builder.append(current.getValue()._text); current = _huffmanTree; } } return builder.toString();
  • 168. } private class CountPair{ int _count; String _text; private CountPair(String text, int count){ _text = text; _count = count; } } private class CountPairTreeComparator implements Comparator<BinaryTree<CountPair>>{ @Override public int compare(BinaryTree<CountPair> t1, BinaryTree<CountPair> t2) { CountPair p1 = t1.getValue(); CountPair p2 = t2.getValue(); if (p1._count != p2._count){ return p2._count - p1._count; }else if (p1._text.length() != p2._text.length()){ return -p1._text.length() - p2._text.length(); } else{ return p1._text.compareTo(p2._text); } } } }
  • 169. 1/1/13 9:26 PMCS 211 Homework Five — Fall 2012 Page 1 of 4http://web.cs.mtholyoke.edu/~candrews/cs211/homework/hw5. html CS 212 — Homework Five Can't see the forest... Due: 30 October 2012, 11:59p Worth: 75 points Part One: Implement a Binary Tree Worth: 15 points The first step is to build a simple BinaryTree ADT (so it should support generics). Our needs for the tree are pretty simple, so you will only need to implement the following interface: BinaryTree(BinaryTree<E> left, E value, BinaryTree<E> right) BinaryTree<E> getLeftChild() BinaryTree<E> getRightChild() void setLeftChild(BinaryTree<E>) void setRightChild(BinaryTree<E>) void setValue(E) E getValue() boolean isLeaf() For this tree, you will be implementing it in "linked-list" style, as described in class. For the second part of the assignment you will be doing a lot of merging of the binary
  • 170. trees and that would be something of a pain that outweighs the trouble of the extra null references. I, of course, expect to see JUnit tests included with this class. Part Two: Parsing Expressions Worth: 60 points One use of trees is to build expression trees. For this assignment, you will be building an arithmetic expression tree that can represent arithmetic expressions. The idea behind expression trees is that inner nodes are operators (in our case, +,-,*,/), and the leaves are operands (either constant values or variables). The value of an expression tree is either the value stored in the node (if the node has no children) or the result of applying the operator stored in the node to its left and right subtrees. So, for example, the expression x + 5 - 6 would be represented as: Your task will be to read in an expression, parse it into a tree, and then let the user perform some basic operations on the expression. You will create a class called ArithmeticExpression with the following 1/1/13 9:26 PMCS 211 Homework Five — Fall 2012 Page 2 of 4http://web.cs.mtholyoke.edu/~candrews/cs211/homework/hw5. html interface:
  • 171. ArithmeticExpression(String expression) [25 pts] This is the constructor. It will take a String containing the expression. The expression will contain operators (+,- ,*,/), integer constants, and arbitrary strings that should be interpreted as variables.There is no guarantee that this expression is valid. If the expression is not valid, this should throw a ParseException (be sure to indicate where you had a problem with the parse). To make your lives a little easier, the expression will be space delimitated. Being the constructor, this function should only perform the parse a build the resulting data structure (using a BinaryTree, of course). String toString() [10 pts] This method should return a String containing the parsed expression. In this case, that means fully parenthesized according to operator precedence (i.e., * and / have higher precedence than + and -). For example, "6 + 5 * 2" should result in "(6+(5*2))". The result should contain no spaces. Hint: this should sound like some kind of traversal — what kind? void setVariable(String name, int value) [10 pts] This allows the user to set a value for a variable in the expression. If the variable does not exist in the function, throw a NotBoundException. int evaluate() [15 pts] Obviously, this should return the integer result of evaluating the expression. Unset variables should be considered to have the value of 0. Example usage Code:
  • 172. ArithmeticExpression expression = new ArithmeticExpression("x + 5 * 6"); System.out.println(expression); expression.setVariable("x", 5); System.out.println(expression.evaluate()); expression.setVariable("x", 10); System.out.println(expression.evaluate()); Output: (x+(5*6)) 35 40 Implementation details The hardest part of this is implementing the parser that builds the expression tree so that the correct operator precedence is maintained. For example, given the expression x + y * 2, assuming that we interpret the left and right sides of the operators as left and right children, there are two trees we could build, but only one of them is correct. 1/1/13 9:26 PMCS 211 Homework Five — Fall 2012 Page 3 of 4http://web.cs.mtholyoke.edu/~candrews/cs211/homework/hw5. html So, we can't just start chaining nodes together. Instead, we are going to use a pair of Stacks to help us
  • 173. out (that's right, you'll need to pull out your Stack class from the first homework). One stack will be the operator stack, and it will hold operators that we don't know how to use yet. The other stack will be a tree stack, and will hold the partial binary trees that we have not fit together yet. As we read tokens from the input expression, the operation will then be: If the token is an operand, make it into a tree and push it on the tree stack If the token is an operator, operator stack is empty OR the operator is either * or /, push the operator on the operator stack Otherwise: While the operator stack is not empty Pop an operator from the operator stack Pop the top two trees from the tree stack Create a new tree with the two trees and the operator Push the new tree on the tree stack Push the new operator onto the operator stack When the String is consumed, repeat the above loop to clear out any unused operators At the end, the expression tree should be sitting alone in the tree stack. Clearly, if any of the pops fail, or if there are more trees in the tree stack at the end of the process, the expression was invalid. Another issue you will have is storing the variable values. The obvious answer would be to replace any variables in the tree with the value when they get set. Of course, then you won't be able to change the variable's value and re-evaluate the expression (which would rather remove the value of having variables there). So, we want to build a lookup table to hold the current
  • 174. values of all of the variables. Very soon, we will start talking about a data structure tailor-made for this purpose, but for right now we will just use an ArrayList. You will need to create some kind of inner class to hold name/value pairs. Stick these in the ArrayList and just iterate through everything to find the right entry. This isn't terribly efficient, but we are unlikely to have very many variables. Very soon, we will start talking about a data structure that is tailor-made to this, but for right now we will put up with this little bit of inefficiency. Bonus round I decided that I would give you the opportunity to earn a little extra credit on this one. If you chose to do any of these, be very clear that you did it in your comments, and provide appropriate test cases demonstrating them in action. (4 points) Adjust your code so that it can handle input strings without spaces. (4 points) Handle implicit multiplication on variables (i.e., 2x + 5). (5 points) Rewrite the parser so that it can handle parentheses in the input string. You will have to think a little bit about how to handle the logic of this case since the parentheses affect the precedence of operations (i.e., they will not be represented in the tree, they will affect the structure of the tree). (5 points) Allow for unary operators. A unary operator would be an operator that takes only a single operand (i.e., -5 or +34). Again, you will have to think about how to change the logic of the parse to allow these
  • 175. (5 points) Write a new method called toPostfixString() that will return the expression in postfix form. Turning the assignment in... Commented source files and tests should be put into a single directory, zipped, tarred or jarred, and submitted online into your course dropbox on ella (I only want source files, I do not want any class files). Please name your files cs211_pid_hw5.suffix, where pid is your Mount Holyoke email account name and suffix is the appropriate suffix for your archive format. Last modified: Tue Oct 23 18:03:05 EDT 2012 1/1/13 9:26 PMCS 211 Homework Five — Fall 2012 Page 4 of 4http://web.cs.mtholyoke.edu/~candrews/cs211/homework/hw5. html 1/1/13 9:26 PM Page 1 of 5http://web.cs.mtholyoke.edu/~candrews/cs211/examples/RBMa p.html import java.util.Set; import java.util.TreeSet;
  • 176. /** * This is a skeleton of a red black tree. The basic functionality of a map backed by a binary search tree is provided, but * the red black handling has been left as an exercise. * * @author C. Andrews * * @param <K> the key type of the Map * @param <V> the value type associated with the key */ public class RBMap<K extends Comparable<K>, V> implements Map<K, V> { private static enum NodeColor {RED, BLACK}; BinaryTree<Pair> _root =null; Set<K> _keys; public RBMap(){ _keys = new TreeSet<K>(); } /** * Add an element to the map. * * If the key is already present in the map, the value is replaced with {@code value}. * * @param key the key to associate the value with * @param value the value being added to the map */ @Override public void put(K key, V value) { BinaryTree<Pair> tmp = new BinaryTree<Pair>(null, new Pair(key, value), null); BinaryTree<Pair> current = _root; BinaryTree<Pair> parent = null; _keys.add(key);
  • 177. while (current != null){ parent = current; if (key.compareTo(current.getValue()._key) == 0){ // they are the same, just update the value current.getValue()._value = value; return; }else if (key.compareTo(current.getValue()._key) < 0){ // the key is smaller, go left current = current.getLeft(); }else{ // the key is larger, go right current = current.getRight(); } } tmp.setParent(parent); if (parent == null){ _root = tmp; }else{ if (key.compareTo(parent.getValue()._key) < 0){ parent.setLeft(tmp); }else{ parent.setRight(tmp); } } // TODO rebalance the tree } /** * Perform a lookup in the map based on the input key.
  • 178. 1/1/13 9:26 PM Page 2 of 5http://web.cs.mtholyoke.edu/~candrews/cs211/examples/RBMa p.html * * @param key the key associated with the value to be returned */ @Override public V get(K key) { BinaryTree<Pair> tmp = find(key); if(tmp == null) return null; else return tmp.getValue()._value; } /** * This private method finds nodes in the tree based on the key value. * * If the key exists in the map, this returns the node associated with it (not just the value). If the * key is not present, this returns null. This is used to implement get and remove. * * @param key the key that we are looking for * @return the node containing the key or null if the key is not present */ private BinaryTree<Pair> find(K key){ BinaryTree<Pair> current = _root;
  • 179. while (current != null && key.compareTo(current.getValue()._key) != 0){ if (key.compareTo(current.getValue()._key) < 0){ current = current.getLeft(); }else{ current = current.getRight(); } } if (current != null) return current; else return null; } /** * Does the map contain the given key? * * @param key the key value to look for in the map * @return a boolean value indicating if the key is present */ @Override public boolean containsKey(K key) { return get(key) != null; } /** * Remove the value associated with {@code key} from the map. * * Removes the key and value pair and returns the value. * * @param key the key for the value we are trying to remove * @return the value associated with the key or null if the key is not present in the map */
  • 180. @Override public V remove(K key) { _keys.remove(key); BinaryTree<Pair> toRemove = find(key); BinaryTree<Pair> child; V value; if (toRemove == null){ return null; } value = toRemove.getValue()._value; if (toRemove.getLeft() != null && toRemove.getRight() != null){ BinaryTree<Pair>tmp = toRemove; NodeColor color = toRemove.getValue()._color; 1/1/13 9:26 PM Page 3 of 5http://web.cs.mtholyoke.edu/~candrews/cs211/examples/RBMa p.html toRemove = successor(toRemove); tmp.setValue( toRemove.getValue()); tmp.getValue()._color = color; } if (toRemove.getLeft() != null){ child = toRemove.getLeft(); }else{ child = toRemove.getRight(); } if (child != null){ child.setParent(toRemove.getParent());
  • 181. } if (toRemove.getParent() == null){ _root = child; }else if (toRemove.getParent().getLeft() == toRemove){ toRemove.getParent().setLeft(child); }else{ toRemove.getParent().setRight(child); } // TODO rebalance tree if necessary return value; } /** * Return the set of all keys present in the map. * * @return the {@code Set} of all keys in the map */ @Override public Set<K> keySet() { return _keys; } /** * A private helper that finds the immediate successor of a node in the tree. * * @param t the node we are trying to find the successor of * @return the immediate successor of the node or null if there isn't one */ private BinaryTree<Pair> successor(BinaryTree<Pair> t){ if (t.getRight() != null){ return minimum(t.getRight()); }
  • 182. BinaryTree<Pair> parent = t.getParent(); while (parent != null && parent.getRight() == t){ t = parent; parent = parent.getParent(); } return parent; } /** * A private helper that finds the minimum value in the tree rooted at t. * * This will fail if t is null since that would be an invalid operation. * * @param t the subtree we are exploring * @return the minimum value in t */ private BinaryTree<Pair> minimum(BinaryTree<Pair> t){ while (t.getLeft() != null){ t = t.getLeft(); } return t; } 1/1/13 9:26 PM Page 4 of 5http://web.cs.mtholyoke.edu/~candrews/cs211/examples/RBMa p.html /**
  • 183. * A private helper that finds the maximum value in the tree rooted at t. * * This will fail if t is null since that would be an invalid operation. * * @param t the subtree we are exploring * @return the maximum value in t */ @SuppressWarnings("unused") private BinaryTree<Pair> maximum(BinaryTree<Pair> t){ while (t.getRight() != null){ t = t.getRight(); } return t; } /** * Returns a String representation of the tree. * * The representation is a preorder traversal of the tree in which each node is printed out in the * form of the key, followed by a colon and then a B or an R, all in square brackets. So a tree * with root 5 and children 3 and 9 would look like [5:B][3:R][9:R]. * */ public String toString(){ // TODO implement this method } /** * Returns the black height of the tree. * * If there are any violations, this returns -1.
  • 184. * * @return the black height or -1 if there are any violations */ public int blackHeight(){ // TODO implement this method } /** * Indicates if there is a red violation in the tree * * @return a boolean value that indicates if there is a red violation in the tree */ public boolean redViolation(){ // TODO implement this method } /** * This is a simple wrapper class that provides the associations in the tree. * * @author C. Andrews * */ private class Pair{ private K _key; private V _value; private NodeColor _color; private Pair(K key, V value){ _key = key; _value =value; _color = NodeColor.RED; // all new nodes are RED }
  • 185. 1/1/13 9:26 PM Page 5 of 5http://web.cs.mtholyoke.edu/~candrews/cs211/examples/RBMa p.html } }