SlideShare ist ein Scribd-Unternehmen logo
1 von 185
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());
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx

Weitere ähnliche Inhalte

Ähnlich wie META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx

Please add-modify the following to the original code using C# 1- Delet.docx
Please add-modify the following to the original code using C# 1- Delet.docxPlease add-modify the following to the original code using C# 1- Delet.docx
Please add-modify the following to the original code using C# 1- Delet.docxStewartt0kJohnstonh
 
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Sunil Kumar Gunasekaran
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)Tak Lee
 
The concept of stack is extremely important in computer science and .pdf
The concept of stack is extremely important in computer science and .pdfThe concept of stack is extremely important in computer science and .pdf
The concept of stack is extremely important in computer science and .pdfarihantsherwani
 
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...davidwarner122
 
Write a program that will test a name) method no sorting routine from.docx
 Write a program that will test a name) method no sorting routine from.docx Write a program that will test a name) method no sorting routine from.docx
Write a program that will test a name) method no sorting routine from.docxajoy21
 
Please review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdfPlease review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdffathimafancyjeweller
 
1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdfafgt2012
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfaromanets
 
Given an expression string exp, write a java class ExpressionCheccke.pdf
Given an expression string exp, write a java class ExpressionCheccke.pdfGiven an expression string exp, write a java class ExpressionCheccke.pdf
Given an expression string exp, write a java class ExpressionCheccke.pdfinfo382133
 
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfJAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfarpaqindia
 
Given the code below create a method called, getCollisionCount that .pdf
Given the code below create a method called, getCollisionCount that .pdfGiven the code below create a method called, getCollisionCount that .pdf
Given the code below create a method called, getCollisionCount that .pdfaucmistry
 
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfUsing NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfsiennatimbok52331
 
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdfJAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdffantasiatheoutofthef
 
How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdfHow do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdfmail931892
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfarjuncorner565
 
Please help me to make a programming project I have to sue them today- (1).pdf
Please help me to make a programming project I have to sue them today- (1).pdfPlease help me to make a programming project I have to sue them today- (1).pdf
Please help me to make a programming project I have to sue them today- (1).pdfseoagam1
 
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdfHow do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdfmail931892
 

Ähnlich wie META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx (20)

Please add-modify the following to the original code using C# 1- Delet.docx
Please add-modify the following to the original code using C# 1- Delet.docxPlease add-modify the following to the original code using C# 1- Delet.docx
Please add-modify the following to the original code using C# 1- Delet.docx
 
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)
 
The concept of stack is extremely important in computer science and .pdf
The concept of stack is extremely important in computer science and .pdfThe concept of stack is extremely important in computer science and .pdf
The concept of stack is extremely important in computer science and .pdf
 
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
 
Write a program that will test a name) method no sorting routine from.docx
 Write a program that will test a name) method no sorting routine from.docx Write a program that will test a name) method no sorting routine from.docx
Write a program that will test a name) method no sorting routine from.docx
 
Please review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdfPlease review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdf
 
1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf1- The design of a singly-linked list below is a picture of the functi (1).pdf
1- The design of a singly-linked list below is a picture of the functi (1).pdf
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
 
Given an expression string exp, write a java class ExpressionCheccke.pdf
Given an expression string exp, write a java class ExpressionCheccke.pdfGiven an expression string exp, write a java class ExpressionCheccke.pdf
Given an expression string exp, write a java class ExpressionCheccke.pdf
 
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfJAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
 
Given the code below create a method called, getCollisionCount that .pdf
Given the code below create a method called, getCollisionCount that .pdfGiven the code below create a method called, getCollisionCount that .pdf
Given the code below create a method called, getCollisionCount that .pdf
 
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfUsing NetBeansImplement a queue named QueueLL using a Linked List .pdf
Using NetBeansImplement a queue named QueueLL using a Linked List .pdf
 
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdfJAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
 
How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdfHow do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
 
Please help me to make a programming project I have to sue them today- (1).pdf
Please help me to make a programming project I have to sue them today- (1).pdfPlease help me to make a programming project I have to sue them today- (1).pdf
Please help me to make a programming project I have to sue them today- (1).pdf
 
ScalaFlavor4J
ScalaFlavor4JScalaFlavor4J
ScalaFlavor4J
 
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdfHow do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
 

Mehr von andreecapon

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

Mehr von andreecapon (20)

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

Kürzlich hochgeladen

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxAmita Gupta
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 

Kürzlich hochgeladen (20)

Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 

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());