inital commit
This commit is contained in:
commit
d1948b0e58
37
.gitignore
vendored
Normal file
37
.gitignore
vendored
Normal file
|
@ -0,0 +1,37 @@
|
|||
# Created by https://www.toptal.com/developers/gitignore/api/java
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=java
|
||||
|
||||
### Java ###
|
||||
# Compiled class file
|
||||
*.class
|
||||
|
||||
# Log file
|
||||
*.log
|
||||
|
||||
# BlueJ files
|
||||
*.ctxt
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.nar
|
||||
*.ear
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.rar
|
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/java
|
||||
|
||||
#uploading only code, not compile settings.
|
||||
*.xml
|
||||
*.properties
|
||||
|
||||
#word docs for assignment submission (I have no clue why our professor insited on copying and pasting source code into *word docs*.
|
||||
*.docx
|
||||
*.doc
|
Binary file not shown.
193
IteratorExample1/src/Alphabet.java
Normal file
193
IteratorExample1/src/Alphabet.java
Normal file
|
@ -0,0 +1,193 @@
|
|||
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author latimer
|
||||
* @version 1.00 03/03/16
|
||||
*
|
||||
* Example of an Iterator for the LinkedPositionalList class.
|
||||
*
|
||||
*/
|
||||
public class Alphabet {
|
||||
|
||||
private LinkedPositionalList<Letter> alphabet = null;
|
||||
|
||||
//
|
||||
// Constructor builds a LinkedPositionalList of Letters.
|
||||
//
|
||||
public Alphabet( ){
|
||||
|
||||
alphabet = new LinkedPositionalList<>();
|
||||
|
||||
String alphabetString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
|
||||
Letter nextLetter;
|
||||
|
||||
for ( int i = 0; i < alphabetString.length(); i++ )
|
||||
|
||||
{
|
||||
nextLetter = new Letter( alphabetString.charAt(i) );
|
||||
alphabet.addLast( nextLetter );
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isVowel( String s )
|
||||
{
|
||||
return ( s.equals("A") || s.equals("E") || s.equals("I") || s.equals("O") || s.equals("U") );
|
||||
}
|
||||
|
||||
//
|
||||
// This method uses an iterator to traverse the list.
|
||||
//
|
||||
// Note that here we are using the nested iterator classes from the
|
||||
// LinkedPositionalList class and not ones for the Alphabet class.
|
||||
//
|
||||
@Override
|
||||
public String toString( )
|
||||
{
|
||||
String returnString = "";
|
||||
|
||||
Iterator<Letter> listIterator = alphabet.iterator();
|
||||
|
||||
while ( listIterator.hasNext() )
|
||||
returnString += listIterator.next() + " ";
|
||||
|
||||
return returnString;
|
||||
}
|
||||
|
||||
//
|
||||
// The following classes are the nested Iterator classes from
|
||||
// Code Fragment 7.14
|
||||
//
|
||||
// Only the classes for the Position Itertor have bee included.
|
||||
//
|
||||
// These fragements have been modified so that they are specific to the
|
||||
// Alphabet class.
|
||||
//
|
||||
// It is necessary to put the iterator code here since we want to create
|
||||
// iterators specifically for the Alphabet class which is a concrete class
|
||||
// based on the generic ADT LinkedPositionalList.
|
||||
//
|
||||
// Our code needs to have knowledge of Letter.
|
||||
//
|
||||
// Generally the Generic placeholders <E> have been replaced with
|
||||
// concret references <Letter>
|
||||
// AND
|
||||
// Call to LinkedPositionalList methods have be replaced by calls using
|
||||
// the instance reference alphabet
|
||||
// e.g.
|
||||
// private Position<Letter> cursor = first();
|
||||
// became
|
||||
// private Position<Letter> cursor = alphabet.first();
|
||||
//
|
||||
|
||||
//----- nested PositionIterator class -----
|
||||
private class PositionIterator implements Iterator<Position<Letter>>{
|
||||
private Position<Letter> cursor = alphabet.first(); // position of the next element to report
|
||||
private Position<Letter> recent = null; // position of last reported element
|
||||
/** Tests whether the iterator has a next object. */
|
||||
@Override
|
||||
public boolean hasNext( ) { return ( cursor != null ); }
|
||||
/** Returns the next position in the iterator. */
|
||||
@Override
|
||||
public Position<Letter> next( ) throws NoSuchElementException {
|
||||
if ( cursor == null ) throw new NoSuchElementException( "nothing left " );
|
||||
recent = cursor;
|
||||
cursor = alphabet.after( cursor );
|
||||
return recent;
|
||||
}
|
||||
/** Removes the element returned by most recent call to next. */
|
||||
@Override
|
||||
public void remove( ) throws IllegalStateException {
|
||||
if ( recent == null ) throw new IllegalStateException( "nothing to remove" );
|
||||
alphabet.remove( recent ); // remove from outer list
|
||||
recent = null; // do not allow remove again until next is called
|
||||
}
|
||||
} //----- end of nested PositionIterator class -----
|
||||
|
||||
//----- nested PositionIterable class -----
|
||||
private class PositionIterable implements Iterable<Position<Letter>>{
|
||||
@Override
|
||||
public Iterator<Position<Letter>> iterator( ) { return new PositionIterator( ); }
|
||||
} //----- end of nested PositionIterable class -----
|
||||
|
||||
/** Returns an iterable representation of the list's positions.
|
||||
* @return */
|
||||
public Iterable<Position<Letter>> positions( ) {
|
||||
return new PositionIterable( ); // create a new instace of the inner class
|
||||
}
|
||||
|
||||
//
|
||||
// Below are the nested iterator classes modified to iterate over just the
|
||||
// vowels in a the alphabet list
|
||||
//
|
||||
// Aside from taking care of name conflicts the only real modification
|
||||
// that is necessary is in the next() method betweeen the lines:
|
||||
// recent = cursor;
|
||||
// << modification goes here
|
||||
// return recent;
|
||||
//
|
||||
// This is because cursor points to the Position that will be returned
|
||||
// the "next" time next() is called so:
|
||||
// after saving the value of cursor to recent
|
||||
// cursor is advanced to the next desired location
|
||||
// -- you customize where the cursor is advanced to.
|
||||
// then the value of recent is returned.
|
||||
//
|
||||
// You can create additional custom iterators by making additional copies
|
||||
// of the nested iterator classes, adjusting the names, and modifying
|
||||
// how the value of cursor is updated on each call to next().
|
||||
//
|
||||
|
||||
//----- nested PositionIterator class -----
|
||||
private class VowelPositionIterator implements Iterator<Position<Letter>>{
|
||||
private Position<Letter> cursor = alphabet.first(); // position of the next element to report
|
||||
private Position<Letter> recent = null; // position of last reported element
|
||||
/** Tests whether the iterator has a next object. */
|
||||
@Override
|
||||
public boolean hasNext( ) { return ( cursor != null ); }
|
||||
/** Returns the next position in the iterator. */
|
||||
@Override
|
||||
public Position<Letter> next( ) throws NoSuchElementException {
|
||||
// On the first call to next (i.e. when recent == null) you need to //<<< new code
|
||||
// advance recent until it is pointing to a vowel element. //<<< new code
|
||||
if ( recent == null ) //<<< new code
|
||||
{ //<<< new code
|
||||
while ( cursor != null && !isVowel( cursor.getElement().letter) ) //<<< new code
|
||||
cursor = alphabet.after( cursor ); //<<< new code
|
||||
} //<<< new code
|
||||
|
||||
if ( cursor == null ) throw new NoSuchElementException( "nothing left " );
|
||||
recent = cursor;
|
||||
cursor = alphabet.after( cursor );
|
||||
|
||||
// advance cursor to the next vowel
|
||||
|
||||
while ( cursor != null && !isVowel( cursor.getElement().letter) )
|
||||
cursor = alphabet.after( cursor );
|
||||
|
||||
return recent;
|
||||
}
|
||||
/** Removes the element returned by most recent call to next. */
|
||||
@Override
|
||||
public void remove( ) throws IllegalStateException {
|
||||
if ( recent == null ) throw new IllegalStateException( "nothing to remove" );
|
||||
alphabet.remove( recent ); // remove from outer list
|
||||
recent = null; // do not allow remove again until next is called
|
||||
}
|
||||
} //----- end of nested PositionIterator class -----
|
||||
|
||||
//----- nested PositionIterable class -----
|
||||
private class VowelPositionIterable implements Iterable<Position<Letter>>{
|
||||
@Override
|
||||
public Iterator<Position<Letter>> iterator( ) { return new VowelPositionIterator( ); }
|
||||
} //----- end of nested PositionIterable class -----
|
||||
|
||||
/** Returns an iterable representation of the list's positions.
|
||||
* @return */
|
||||
public Iterable<Position<Letter>> vowelPositions( ) {
|
||||
return new VowelPositionIterable( ); // create a new instace of the inner class
|
||||
}
|
||||
|
||||
}
|
10
IteratorExample1/src/Iterable.java
Normal file
10
IteratorExample1/src/Iterable.java
Normal file
|
@ -0,0 +1,10 @@
|
|||
/**
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrick, Tamassia, Goldwasser
|
||||
* Section 7.4.1
|
||||
*/
|
||||
public interface Iterable<E> {
|
||||
|
||||
Iterator<E> iterator( ); // Returns an iterator of the elements in the collection
|
||||
|
||||
}
|
20
IteratorExample1/src/Iterator.java
Normal file
20
IteratorExample1/src/Iterator.java
Normal file
|
@ -0,0 +1,20 @@
|
|||
/**
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrick, Tamassia, Goldwasser
|
||||
* Section 7.4
|
||||
*/
|
||||
public interface Iterator<E> {
|
||||
|
||||
boolean hasNext( ); // Returns true if there is at least one additional
|
||||
// element in the sequence, and false otherwise.
|
||||
|
||||
E next( ); // Returns the next element in the sequence.
|
||||
|
||||
void remove( ) throws IllegalStateException;
|
||||
// Removes from the collection the element returned by
|
||||
// the most recent call to next( ). Throws an
|
||||
// IllegalStateException if next has not yet been called,
|
||||
// or if remove was already called since the most recent
|
||||
// call to next.
|
||||
|
||||
}
|
91
IteratorExample1/src/IteratorExample1Client.java
Normal file
91
IteratorExample1/src/IteratorExample1Client.java
Normal file
|
@ -0,0 +1,91 @@
|
|||
|
||||
/**
|
||||
*
|
||||
* @author latimer
|
||||
* @version 1.00 03/03/16
|
||||
*
|
||||
* Example of an Iterator for the LinkedPositionalList class.
|
||||
*
|
||||
*/
|
||||
public class IteratorExample1Client {
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
//
|
||||
// Create an instance of the Alphabet class which is
|
||||
// just a LinkedPositiionalList of Letters.
|
||||
//
|
||||
|
||||
Alphabet alphabet = new Alphabet();
|
||||
|
||||
//
|
||||
// Look at the toString( ) method in the Alphabet class.
|
||||
// This method uses a iterator to move across the list
|
||||
//
|
||||
|
||||
System.out.println( "Using toString() alphabet = " + alphabet.toString() );
|
||||
System.out.print("\n");
|
||||
|
||||
//
|
||||
// Let's create an Iterator for the LinkedPositionalList
|
||||
//
|
||||
// Decision: Do you want a PositionInterator or an ElementIterator?
|
||||
//
|
||||
// Let's pick the PositionIterator.
|
||||
//
|
||||
// Since the PositionIterator class is a private class nested in
|
||||
// the LinkedPositionalList class we cannot call the class methods
|
||||
// directly.
|
||||
//
|
||||
// The PositionalIterable class is also a private class nested in
|
||||
// the LinkedPositionalList class that we cannot call the class methods
|
||||
// directly.
|
||||
//
|
||||
// Fortunately (or perhaps by design) the Iterable class is a public
|
||||
// class nexted in LinkedPositionalList class so we can call its
|
||||
// class methods directly.
|
||||
//
|
||||
// This class has one method "positions()" that generally
|
||||
// returns an object of type IterablePositions<E>
|
||||
// and in our specific case
|
||||
// returns an object of type IterablePostions<Letter>
|
||||
//
|
||||
// The object returned by "positions()" gives us access to the
|
||||
// nested private class PositionIterable class that returns an
|
||||
// PositionIterator object.
|
||||
//
|
||||
// The PositionIterator object is the iterator.
|
||||
//
|
||||
|
||||
Iterator<Position<Letter>> letterListIterator = alphabet.positions().iterator();
|
||||
|
||||
System.out.print("Using letterListIterator alphabet = ");
|
||||
while ( letterListIterator.hasNext() )
|
||||
System.out.print( letterListIterator.next().getElement().toString() + " " );
|
||||
System.out.print( "\n\n" );
|
||||
|
||||
//
|
||||
// This seems like a lot of work to traverse a list but provided we have
|
||||
// access to the Iterator classes we can build an iterator to traverse
|
||||
// the list without any knowledge of how the list is implemented.
|
||||
//
|
||||
// Also we have the opportunity to build customized iterators that
|
||||
// allow us the specify how we will traverse the list.
|
||||
//
|
||||
// For example we may want to build an iterator that moves accross all
|
||||
// of the vowels in the alphabet.
|
||||
//
|
||||
// To do this we create a nested interator class inside of our
|
||||
// Alphabet class.
|
||||
//
|
||||
|
||||
Iterator<Position<Letter>> vowelListIterator = alphabet.vowelPositions().iterator();
|
||||
|
||||
System.out.print("Using VowelListIterator alphabet = ");
|
||||
while ( vowelListIterator.hasNext() )
|
||||
System.out.print( vowelListIterator.next().getElement().toString() + " " );
|
||||
System.out.print( "\n\n" );
|
||||
|
||||
}
|
||||
}
|
25
IteratorExample1/src/Letter.java
Normal file
25
IteratorExample1/src/Letter.java
Normal file
|
@ -0,0 +1,25 @@
|
|||
/**
|
||||
*
|
||||
* @author latimer
|
||||
* @version 1.00 03/03/16
|
||||
*
|
||||
* A simple Letter class that holds a single char element as a upper case String.
|
||||
*
|
||||
*/
|
||||
public class Letter {
|
||||
|
||||
String letter;
|
||||
|
||||
public Letter() { }
|
||||
|
||||
public Letter( String letter ) { this.letter = letter; }
|
||||
|
||||
public Letter( char letter ) {
|
||||
String newLetter = "" + letter;
|
||||
this.letter = newLetter.toUpperCase();
|
||||
}
|
||||
|
||||
public String toString( ){
|
||||
return letter;
|
||||
}
|
||||
}
|
310
IteratorExample1/src/LinkedPositionalList.java
Normal file
310
IteratorExample1/src/LinkedPositionalList.java
Normal file
|
@ -0,0 +1,310 @@
|
|||
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/**
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrick, Tamassia, Goldwasser
|
||||
* Code Fragements 7.9, 7.10, 7.11, 7.12 & 7.14
|
||||
*
|
||||
* toString method added by Latimer
|
||||
*/
|
||||
|
||||
/** Implementation of a positional list stored as a doubly linked list. */
|
||||
public class LinkedPositionalList<E> implements PositionalList<E> {
|
||||
|
||||
//----- nested Node class -----
|
||||
|
||||
private static class Node<E> implements Position<E> {
|
||||
|
||||
private E element; // reference to the element stored at this node
|
||||
private Node<E> prev; // reference to the prevous node in the list
|
||||
private Node<E> next; // reference to the subsequent node in the list
|
||||
|
||||
public Node( E e, Node<E> p, Node<E> n ){
|
||||
element = e;
|
||||
prev = p;
|
||||
next = n;
|
||||
}
|
||||
|
||||
@Override
|
||||
public E getElement( ) throws IllegalStateException
|
||||
{
|
||||
if ( next == null )
|
||||
throw new IllegalStateException( "Position no longer valid." );
|
||||
return element;
|
||||
}
|
||||
|
||||
public Node<E> getPrev( )
|
||||
{
|
||||
return prev;
|
||||
}
|
||||
|
||||
public Node<E> getNext( )
|
||||
{
|
||||
return next;
|
||||
}
|
||||
|
||||
public void setElemetn( E e )
|
||||
{
|
||||
element = e;
|
||||
}
|
||||
|
||||
public void setPrev( Node<E> p )
|
||||
{
|
||||
prev = p;
|
||||
}
|
||||
|
||||
public void setNext( Node<E> n )
|
||||
{
|
||||
next = n;
|
||||
}
|
||||
} //----- end of nested Node class -----
|
||||
|
||||
/**
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrick, Tamassia, Goldwasser
|
||||
* Code Fragement 7.14
|
||||
*/
|
||||
|
||||
//----- nested PositionIterator class -----
|
||||
private class PositionIterator implements Iterator<Position<E>>{
|
||||
private Position<E> cursor = first(); // position of the next element to report
|
||||
private Position<E> recent = null; // position of last reported element
|
||||
/** Tests whether the iterator has a next object. */
|
||||
@Override
|
||||
public boolean hasNext( ) { return ( cursor != null ); }
|
||||
/** Returns the next position in the iterator. */
|
||||
@Override
|
||||
public Position<E> next( ) throws NoSuchElementException {
|
||||
if ( cursor == null ) throw new NoSuchElementException( "nothing left " );
|
||||
recent = cursor;
|
||||
cursor = after( cursor );
|
||||
return recent;
|
||||
}
|
||||
/** Removes the element returned by most recent call to next. */
|
||||
@Override
|
||||
public void remove( ) throws IllegalStateException {
|
||||
if ( recent == null ) throw new IllegalStateException( "nothing to remove" );
|
||||
LinkedPositionalList.this.remove( recent ); // remove from outer list
|
||||
recent = null; // do not allow remove again until next is called
|
||||
}
|
||||
} //----- end of nested PositionIterator class -----
|
||||
|
||||
//----- nested PositionIterable class -----
|
||||
private class PositionIterable implements Iterable<Position<E>>{
|
||||
@Override
|
||||
public Iterator<Position<E>> iterator( ) { return new PositionIterator( ); }
|
||||
} //----- end of nested PositionIterable class -----
|
||||
|
||||
/** Returns an iterable representation of the list's positions.
|
||||
* @return */
|
||||
public Iterable<Position<E>> positions( ) {
|
||||
return new PositionIterable( ); // create a new instance of the inner class
|
||||
}
|
||||
|
||||
//----- nested ElementIterator class -----
|
||||
/* This class adapts the iteration produced by positions( ) to return elements. */
|
||||
private class ElementIterator implements Iterator<E> {
|
||||
Iterator<Position<E>> posIterator = new PositionIterator( );
|
||||
@Override
|
||||
public boolean hasNext( ) { return posIterator.hasNext( ); }
|
||||
@Override
|
||||
public E next( ) { return posIterator.next( ).getElement( ); } // return element
|
||||
@Override
|
||||
public void remove( ) { posIterator.remove( ); }
|
||||
}
|
||||
|
||||
/** Returns an iterator of the elements stored in the list */
|
||||
public Iterator<E> iterator( ) { return new ElementIterator( ); }
|
||||
|
||||
|
||||
// instance variables of the LinkedPositionalList
|
||||
|
||||
private Node<E> header; // header sentinel
|
||||
private Node<E> trailer; // trailer sentinel
|
||||
private int size = 0; // number of elements in the list
|
||||
|
||||
public LinkedPositionalList( ){
|
||||
header = new Node<>( null, null, null ); // create header
|
||||
trailer = new Node<>( null, header, null ); // create trailer is preceded by header
|
||||
header.setNext(trailer); // header is followed by trailer
|
||||
}
|
||||
|
||||
// private utilities
|
||||
/**
|
||||
* @param p position to validate
|
||||
* @return node if position is valid
|
||||
* @throws IllegalArgumentException if p no longer in list or p is not a position
|
||||
*/
|
||||
private Node<E> validate( Position<E> p ) throws IllegalArgumentException {
|
||||
|
||||
if( !(p instanceof Node )) throw new IllegalArgumentException( "Invalid p" );
|
||||
|
||||
Node<E> node = ( Node<E> ) p; // safe cast
|
||||
|
||||
if ( node.getNext() == null )
|
||||
throw new IllegalArgumentException( "p is no longer in the list" );
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param node to be returned as position if not header or trailer
|
||||
* @return position of node
|
||||
*/
|
||||
private Position<E> position( Node<E> node ){
|
||||
if ( node == header || node == trailer )
|
||||
return null;
|
||||
return node;
|
||||
}
|
||||
|
||||
// public accessor methods
|
||||
|
||||
/**
|
||||
* @return number of elements in linked list
|
||||
*/
|
||||
@Override
|
||||
public int size( ){
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if list is empty, false other wise
|
||||
*/
|
||||
@Override
|
||||
public boolean isEmpty( ){
|
||||
return ( size == 0 );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the first position in linked list (null if empty).
|
||||
*/
|
||||
@Override
|
||||
public Position<E> first( ){
|
||||
return position( header.getNext( ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the last position in linked list (null if empty).
|
||||
*/
|
||||
@Override
|
||||
public Position<E> last( ){
|
||||
return position( trailer.getPrev( ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* @param p position to get position immediately before
|
||||
* @return position before p
|
||||
* @throws IllegalArgumentException if p not valid
|
||||
*/
|
||||
@Override
|
||||
public Position<E> before( Position<E> p ) throws IllegalArgumentException{
|
||||
Node<E> node = validate( p );
|
||||
return position( node.getPrev( ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* @param p position to get immediately after
|
||||
* @return position after p
|
||||
* @throws IllegalArgumentException if p not valid
|
||||
*/
|
||||
@Override
|
||||
public Position<E> after( Position<E> p ) throws IllegalArgumentException{
|
||||
Node<E> node = validate( p );
|
||||
return position( node.getNext( ) );
|
||||
}
|
||||
|
||||
// private utilities
|
||||
|
||||
/**
|
||||
* @param e element to be added
|
||||
* @param pred node to add element after
|
||||
* @param succ node to add element before
|
||||
* @return position of newly added element
|
||||
*/
|
||||
private Position<E> addBetween(E e, Node<E> pred, Node<E> succ ){
|
||||
Node<E> newest = new Node<>(e, pred, succ); // create and link new node
|
||||
pred.setNext(newest);
|
||||
succ.setPrev(newest);
|
||||
size++;
|
||||
return newest;
|
||||
}
|
||||
|
||||
// public update methods
|
||||
|
||||
/**
|
||||
* @param e element to be added just after header
|
||||
* @return position of newly added element
|
||||
*/
|
||||
@Override
|
||||
public Position<E> addFirst(E e) {
|
||||
return addBetween( e, header, header.getNext() );
|
||||
}
|
||||
|
||||
/**
|
||||
* @param e element to be added just before trailer
|
||||
* @return position of newly added element
|
||||
*/
|
||||
@Override
|
||||
public Position<E> addLast( E e ){
|
||||
return addBetween(e, trailer.getPrev( ), trailer );
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param p position to add element before
|
||||
* @param e element to be added
|
||||
* @return position of newly added element
|
||||
* @throws IllegalArgumentException if p is not valid
|
||||
*/
|
||||
@Override
|
||||
public Position<E> addBefore( Position<E> p, E e ) throws IllegalArgumentException {
|
||||
Node<E> node = validate( p );
|
||||
return addBetween(e, node.getPrev( ), node );
|
||||
}
|
||||
|
||||
/**
|
||||
* @param p position to add element after
|
||||
* @param e element to be added
|
||||
* @return position of newly added element
|
||||
* @throws IllegalArgumentException if p is not valid
|
||||
*/
|
||||
@Override
|
||||
public Position<E> addAfter( Position<E> p, E e ) throws IllegalArgumentException {
|
||||
Node<E> node = validate( p );
|
||||
return addBetween(e, node, node.getNext( ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* @param p position of node to update
|
||||
* @param e new element for node
|
||||
* @return old element in node before update
|
||||
* @throws IllegalArgumentException if p not valid
|
||||
*/
|
||||
@Override
|
||||
public E set( Position<E> p, E e ) throws IllegalArgumentException {
|
||||
Node<E> node = validate( p );
|
||||
E answer = node.getElement( );
|
||||
node.setElemetn( e );
|
||||
return answer;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param p position to be removed
|
||||
* @return element that was removed
|
||||
* @throws IllegalArgumentException if p not valid
|
||||
*/
|
||||
public E remove( Position<E> p ) throws IllegalArgumentException {
|
||||
Node<E> node = validate( p );
|
||||
Node<E> predecessor = node.getPrev();
|
||||
Node<E> successor = node.getNext();
|
||||
predecessor.setNext( successor );
|
||||
successor.setPrev( predecessor );
|
||||
size--;
|
||||
E answer = node.getElement( );
|
||||
node.setElemetn( null );
|
||||
node.setNext( null );
|
||||
node.setPrev( null );
|
||||
return answer;
|
||||
}
|
||||
}
|
15
IteratorExample1/src/Position.java
Normal file
15
IteratorExample1/src/Position.java
Normal file
|
@ -0,0 +1,15 @@
|
|||
|
||||
/**
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrick, Tamassia, Goldwasser
|
||||
* Code Fragement 7.7
|
||||
*/
|
||||
public interface Position<E> {
|
||||
/**
|
||||
* Returns the element stored at this position.
|
||||
*
|
||||
* @return the stored element
|
||||
* @thorws IllegalStateExceptoin if position no longer valid
|
||||
*/
|
||||
E getElement( ) throws IllegalStateException;
|
||||
}
|
89
IteratorExample1/src/PositionalList.java
Normal file
89
IteratorExample1/src/PositionalList.java
Normal file
|
@ -0,0 +1,89 @@
|
|||
/**
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrick, Tamassia, Goldwasser
|
||||
* Code Fragement 7.8
|
||||
*/
|
||||
|
||||
/**
|
||||
* An interface for positional lists.
|
||||
*/
|
||||
public interface PositionalList<E> {
|
||||
|
||||
/**
|
||||
* @return the number of elements in the list.
|
||||
*/
|
||||
int size( );
|
||||
|
||||
/**
|
||||
* @return true if the list is empty.
|
||||
*/
|
||||
boolean isEmpty( );
|
||||
|
||||
/**
|
||||
* @return the first Position in the list ( or null, if empty ).
|
||||
*/
|
||||
Position<E> first( );
|
||||
|
||||
/**
|
||||
* @return the last Position in the list ( or null, if empty ).
|
||||
*/
|
||||
Position<E> last( );
|
||||
|
||||
/**
|
||||
* @param p a position in the list,
|
||||
* @return position immediately before p ( or null if p is first ).
|
||||
* @throws IllegalArgumentException if p is not in list.
|
||||
*/
|
||||
Position<E> before( Position<E> p ) throws IllegalArgumentException;
|
||||
|
||||
/**
|
||||
* @param p a position in the list,
|
||||
* @return position immediately after p ( or null if p is last ).
|
||||
* @throws IllegalArgumentException if p is not in list.
|
||||
*/
|
||||
Position<E> after( Position<E> p ) throws IllegalArgumentException;
|
||||
|
||||
/**
|
||||
* @param e element to be inserted at front of list
|
||||
* @return position of inserted element
|
||||
*/
|
||||
Position<E> addFirst( E e );
|
||||
|
||||
/**
|
||||
* @param e element to be inserted at back of list
|
||||
* @return position of inserted element
|
||||
*/
|
||||
Position<E> addLast( E e );
|
||||
|
||||
/**
|
||||
* @param p position to be inserted before
|
||||
* @param e element to be inserted before position p
|
||||
* @return position of e
|
||||
* @throws IllegalArgumentException if p not in list
|
||||
*/
|
||||
Position<E> addBefore( Position<E> p, E e ) throws IllegalArgumentException;
|
||||
|
||||
/**
|
||||
* @param p position to be inserted after
|
||||
* @param e element to be inserted after position p
|
||||
* @return position of e
|
||||
* @throws IllegalArgumentException if p not in list
|
||||
*/
|
||||
Position<E> addAfter( Position<E> p, E e ) throws IllegalArgumentException;
|
||||
|
||||
/**
|
||||
* @param p position to store element at
|
||||
* @param e element to be stored at p
|
||||
* @return the element that is replaced
|
||||
* @throws IllegalArgumentException if p is not in list
|
||||
*/
|
||||
E set( Position<E> p, E e ) throws IllegalArgumentException;
|
||||
|
||||
/**
|
||||
* @param p position of element to be removed
|
||||
* @return removed element
|
||||
* @throws IllegalArgumentException if p not in list
|
||||
*/
|
||||
E remove( Position<E> p ) throws IllegalArgumentException;
|
||||
|
||||
}
|
69
JOptionPaneExample/JOptionPaneExample/src/Client.java
Normal file
69
JOptionPaneExample/JOptionPaneExample/src/Client.java
Normal file
|
@ -0,0 +1,69 @@
|
|||
import javax.swing.JOptionPane;
|
||||
|
||||
public class Client {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
showInputDialogExample();
|
||||
|
||||
showInputDialogMenuExample();
|
||||
|
||||
showMessageDialogExample();
|
||||
|
||||
showConfirmDialogExample();
|
||||
|
||||
}
|
||||
|
||||
public static void showInputDialogExample( )
|
||||
{
|
||||
String response;
|
||||
|
||||
response = JOptionPane.showInputDialog( null, "My Question", "My Title", 0 );
|
||||
|
||||
System.out.println("respone = " + response );
|
||||
}
|
||||
|
||||
|
||||
public static void showInputDialogMenuExample()
|
||||
{
|
||||
String response;
|
||||
|
||||
String optionString = "A to run method A\nB to run method B\nC to exit";
|
||||
|
||||
response = JOptionPane.showInputDialog( null, optionString, "My Title", 0 );
|
||||
|
||||
switch ( response )
|
||||
{
|
||||
case "a" :
|
||||
case "A" :
|
||||
System.out.println("Calling method A");
|
||||
break;
|
||||
case "b" :
|
||||
case "B" :
|
||||
System.out.println("Calling method B");
|
||||
break;
|
||||
case "c" :
|
||||
case "C" :
|
||||
System.out.println("Setting sential flag to exit loop");
|
||||
default :
|
||||
System.out.println("Should not be able to get here!!!");
|
||||
}
|
||||
}
|
||||
|
||||
public static void showMessageDialogExample()
|
||||
{
|
||||
String response = "George";
|
||||
|
||||
JOptionPane.showMessageDialog(null, null, response, 0);
|
||||
}
|
||||
|
||||
public static void showConfirmDialogExample()
|
||||
{
|
||||
String response = "Are you sure your name is George?";
|
||||
|
||||
int reply = JOptionPane.showConfirmDialog(null, null, response, 0);
|
||||
|
||||
System.out.println( reply );
|
||||
}
|
||||
|
||||
}
|
621
LICENCE.md
Normal file
621
LICENCE.md
Normal file
|
@ -0,0 +1,621 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you dstribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
3
Lab101-VenbergGE/manifest.mf
Normal file
3
Lab101-VenbergGE/manifest.mf
Normal file
|
@ -0,0 +1,3 @@
|
|||
Manifest-Version: 1.0
|
||||
X-COMMENT: Main-Class will be added automatically by build
|
||||
|
162
Lab101-VenbergGE/src/Client.java
Normal file
162
Lab101-VenbergGE/src/Client.java
Normal file
|
@ -0,0 +1,162 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author toric
|
||||
*/
|
||||
public class Client {
|
||||
public static void main(String[] args) throws FileNotFoundException{
|
||||
File inputFile = new File("/home/toric/Downloads/employeeList.txt"); //TODO!!! change to C:/data/EmployeeList.txt //supposedly with java you can use / on windows as well as linux.
|
||||
Scanner file = new Scanner(inputFile);
|
||||
Scanner scan = new Scanner(System.in);
|
||||
|
||||
final int maxEmployees = 20;
|
||||
|
||||
Employee[] employeeList = new Employee[maxEmployees];
|
||||
|
||||
//declaing the variables we will use in the loop.
|
||||
//im not sure whether or not its best practice to declare inside a loop,
|
||||
//but Im not sure its a good idea to re-instantiate the variable every loop.
|
||||
char employeeType;
|
||||
int id;
|
||||
String name;
|
||||
String titleOrPosition; // can use this for both, saving us a tiny bit of memory.
|
||||
int salary;
|
||||
double hourlyRate;
|
||||
|
||||
//each line is one object
|
||||
for( int i = 0; i<maxEmployees; i++){
|
||||
if(file.hasNextLine()==false){
|
||||
break;
|
||||
}
|
||||
|
||||
employeeType = file.next().charAt(0); //comparing with a single char string was giving me strange results.
|
||||
id = file.nextInt();
|
||||
name = file.next();
|
||||
titleOrPosition = file.next();
|
||||
if (employeeType == 'S'){
|
||||
salary = file.nextInt();
|
||||
employeeList[i]= new Salaried(name, titleOrPosition, id, salary);
|
||||
}
|
||||
else{
|
||||
hourlyRate = file.nextDouble();
|
||||
employeeList[i] = new Hourly(name, titleOrPosition, id, hourlyRate);
|
||||
}
|
||||
file.nextLine();
|
||||
}
|
||||
|
||||
//WHY CANT JAVA JUST HAVE A PRINT() FUNCTION? IT WOULD SAVE ME SO MUCH TYPING!
|
||||
System.out.println("creating salaried employee.");
|
||||
System.out.print("enter the employees name: ");
|
||||
name = scan.next();
|
||||
System.out.println();
|
||||
System.out.print("enter the employees title: ");
|
||||
titleOrPosition = scan.next();
|
||||
System.out.println();
|
||||
System.out.print("enter the employees ID number: ");
|
||||
id = scan.nextInt();
|
||||
System.out.println();
|
||||
System.out.print("enter the employees salary: ");
|
||||
salary = scan.nextInt();
|
||||
System.out.println();
|
||||
//getting how many employees we currently have to figure out where I should put it in the array
|
||||
employeeList[employeeList[0].getEmployeeCount()] =
|
||||
new Salaried(name, titleOrPosition, id, salary);
|
||||
|
||||
System.out.println("creating hourly employee");
|
||||
System.out.print("enter the employees name: ");
|
||||
name = scan.next();
|
||||
System.out.println();
|
||||
System.out.print("enter the employees position: ");
|
||||
titleOrPosition = scan.next();
|
||||
System.out.println();
|
||||
System.out.print("enter the employees ID number: ");
|
||||
id = scan.nextInt();
|
||||
System.out.println();
|
||||
System.out.print("enter the employees hourly wage: ");
|
||||
hourlyRate = scan.nextDouble();
|
||||
System.out.println();
|
||||
employeeList[employeeList[0].getEmployeeCount()] =
|
||||
new Hourly(name, titleOrPosition, id, salary);
|
||||
|
||||
for (int i=0; i < maxEmployees; i++){
|
||||
//cant just let it print the null values, it throws errors if you do.
|
||||
if (employeeList[i] != null){
|
||||
System.out.println(employeeList[i].toString());
|
||||
}
|
||||
else{
|
||||
System.out.println("value is a null value");
|
||||
}
|
||||
}
|
||||
|
||||
for (int i=0; i < maxEmployees; i++){
|
||||
if (employeeList[i] != null){
|
||||
if (employeeList[i] instanceof Salaried){
|
||||
//this FEELS hacky, but other ways Ive tried havent worked. Is there a way to 'cast in place', so to speak?
|
||||
Salaried s = (Salaried) employeeList[i];
|
||||
s.setSalary((int)((double)s.getSalary()*1.1));
|
||||
employeeList[i] = (Employee) s;
|
||||
}
|
||||
else{
|
||||
Hourly h = (Hourly) employeeList[i];
|
||||
h.setHourlyRate(h.getHourlyRate()*1.1);
|
||||
employeeList[i] = (Employee) h;
|
||||
}
|
||||
}
|
||||
else{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i=0; i < maxEmployees; i++){
|
||||
if (employeeList[i] != null){
|
||||
System.out.println(employeeList[i].toString());
|
||||
}
|
||||
else{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//its telling that I choose these names immediately, I read way to many crypto blogs!
|
||||
Employee emp1 = new Employee("bob", 1);
|
||||
Employee emp2 = new Employee("bob", 1);
|
||||
Employee emp3 = new Employee("alice", 2);
|
||||
|
||||
System.out.println(emp1.equals(emp2)+" should be true");
|
||||
System.out.println(emp2.equals(emp3)+" should be false");
|
||||
|
||||
Hourly hour1 = new Hourly("alice", "sysAdmin", 1, 100);
|
||||
Hourly hour2 = new Hourly("alice", "sysAdmin", 1, 100);
|
||||
Hourly hour3 = new Hourly("bob", "dev", 2, 100);
|
||||
|
||||
System.out.println(hour1.equals(hour2)+" should be true");
|
||||
System.out.println(hour2.equals(hour3)+" should be false");
|
||||
|
||||
Salaried sal1 = new Salaried("bob", "sysAdmin", 1, 100);
|
||||
Salaried sal2 = new Salaried("bob", "sysAdmin", 1, 100);
|
||||
Salaried sal3 = new Salaried("alice", "dev", 2, 100);
|
||||
|
||||
System.out.println(sal1.equals(sal2)+" should be true");
|
||||
System.out.println(sal2.equals(sal3)+" should be false");
|
||||
|
||||
}
|
||||
}
|
96
Lab101-VenbergGE/src/Employee.java
Normal file
96
Lab101-VenbergGE/src/Employee.java
Normal file
|
@ -0,0 +1,96 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @author toric
|
||||
* @version 01/25/2021
|
||||
*/
|
||||
public class Employee {
|
||||
private static int employeeCount =0;
|
||||
private int id;
|
||||
private String name;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param name
|
||||
* @param id
|
||||
*/
|
||||
public Employee (String name, int id){
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
employeeCount++;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return id
|
||||
*/
|
||||
public int getID(){return id;}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return name
|
||||
*/
|
||||
public String getName(){return name;}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return employeeCount
|
||||
*/
|
||||
public int getEmployeeCount(){return employeeCount;}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param id sets id
|
||||
*/
|
||||
public void setID(int id){
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param name sets name
|
||||
*/
|
||||
public void setName(String name){
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param o the object to be compared against
|
||||
* @return true if the objects are equal
|
||||
*/
|
||||
public boolean equals( Object o )
|
||||
{
|
||||
if (!(o instanceof Employee)){
|
||||
return false;
|
||||
}
|
||||
Employee e=(Employee)o;
|
||||
return id == e.id
|
||||
&& name.equals( e.name );
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return contents of the instance
|
||||
*/
|
||||
public String toString(){
|
||||
return getClass().getName() + '@' + ':'+name+':'+id+':'+employeeCount;
|
||||
}
|
||||
|
||||
}
|
99
Lab101-VenbergGE/src/Hourly.java
Normal file
99
Lab101-VenbergGE/src/Hourly.java
Normal file
|
@ -0,0 +1,99 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @author toric
|
||||
*/
|
||||
public class Hourly extends Employee{
|
||||
|
||||
private String position;
|
||||
private double hourlyRate;
|
||||
private static int hourlyCount = 0;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param name
|
||||
* @param position
|
||||
* @param id
|
||||
* @param hourlyRate
|
||||
*/
|
||||
public Hourly(String name, String position, int id, double hourlyRate){
|
||||
super(name, id);
|
||||
this.position = position;
|
||||
this.hourlyRate = hourlyRate;
|
||||
hourlyCount++;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return position
|
||||
*/
|
||||
public String getPosition(){return position;}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return hourlyRate
|
||||
*/
|
||||
public double getHourlyRate(){return hourlyRate;}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return hourlyCount
|
||||
*/
|
||||
public int getHourlyCount(){return hourlyCount;}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param position sets position
|
||||
*/
|
||||
public void setPosition(String position){
|
||||
this.position = position;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param hourlyRate sets hourlyRate
|
||||
*/
|
||||
public void setHourlyRate(double hourlyRate){
|
||||
this.hourlyRate = hourlyRate;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param o object to compare against
|
||||
* @return true if contents of object are equal
|
||||
*/
|
||||
public boolean equals (Object o){
|
||||
if (!(o instanceof Hourly)){
|
||||
return false;
|
||||
}
|
||||
Hourly h = (Hourly) o;
|
||||
return super.equals(h)
|
||||
&& position.equals(h.position)
|
||||
&& hourlyRate == h.hourlyRate;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return contents of instance
|
||||
*/
|
||||
public String toString(){
|
||||
return super.toString()+':'+getClass().getName()+'@'+position+':'+hourlyRate;
|
||||
}
|
||||
|
||||
}
|
99
Lab101-VenbergGE/src/Salaried.java
Normal file
99
Lab101-VenbergGE/src/Salaried.java
Normal file
|
@ -0,0 +1,99 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
*@version 01/26/2021
|
||||
* @author toric
|
||||
*/
|
||||
public class Salaried extends Employee {
|
||||
|
||||
private String title;
|
||||
private int salary;
|
||||
private static int salariedCount;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param name
|
||||
* @param title
|
||||
* @param id
|
||||
* @param salary
|
||||
*/
|
||||
public Salaried(String name, String title, int id, int salary){
|
||||
super(name,id);
|
||||
this.title = title;
|
||||
this.salary = salary;
|
||||
salariedCount++;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return title
|
||||
*/
|
||||
public String getTitle(){return title;}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return salary
|
||||
*/
|
||||
public int getSalary(){return salary;}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return salariedCount
|
||||
*/
|
||||
public int getSalariedCount(){return salariedCount;}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param title sets title
|
||||
*/
|
||||
public void setTitle(String title){
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param salary sets salary
|
||||
*/
|
||||
public void setSalary(int salary){
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param o the object to comapre against
|
||||
* @return true if the objects are equal
|
||||
*/
|
||||
public boolean equals (Object o){
|
||||
if (!(o instanceof Salaried)){
|
||||
return false;
|
||||
}
|
||||
Salaried s = (Salaried)o;
|
||||
return super.equals(s)
|
||||
&& title.equals(s.title)
|
||||
&& salary == s.salary;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return String contents of instance
|
||||
*/
|
||||
public String toString(){
|
||||
return super.toString()+':'+getClass().getName()+'@'+title+':'+salary;
|
||||
}
|
||||
|
||||
}
|
3
Lab102-VenbergGE/manifest.mf
Normal file
3
Lab102-VenbergGE/manifest.mf
Normal file
|
@ -0,0 +1,3 @@
|
|||
Manifest-Version: 1.0
|
||||
X-COMMENT: Main-Class will be added automatically by build
|
||||
|
53
Lab102-VenbergGE/src/Client.java
Normal file
53
Lab102-VenbergGE/src/Client.java
Normal file
|
@ -0,0 +1,53 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @version 02/02/2021
|
||||
* @author toric
|
||||
*/
|
||||
public class Client {
|
||||
public static void main(String[] args){
|
||||
|
||||
Scores scores = new Scores(100);
|
||||
|
||||
//dont want to make rand object 100 times...
|
||||
java.util.Random rand = new java.util.Random();
|
||||
for(int i=0; i<100; i++){
|
||||
scores.add(rand.nextInt(201)-100); //the nextint generates between 0 (inclusive) and max(exclusive)
|
||||
}
|
||||
|
||||
System.out.println(scores.toString());
|
||||
|
||||
scores.add(86);
|
||||
|
||||
System.out.println(scores.size());
|
||||
|
||||
scores.remove();
|
||||
|
||||
int pos75 = scores.get(74); //you said to get the 75th number, which is index 74.
|
||||
|
||||
System.out.println(scores.getFrequencyOf(pos75));
|
||||
|
||||
scores.remove(pos75);
|
||||
|
||||
System.out.println(scores.getFrequencyOf(pos75));
|
||||
|
||||
System.out.println(scores.getFrequencyOf(86));
|
||||
|
||||
System.out.println(scores.contains(86));
|
||||
}
|
||||
}
|
205
Lab102-VenbergGE/src/Scores.java
Normal file
205
Lab102-VenbergGE/src/Scores.java
Normal file
|
@ -0,0 +1,205 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @version 01/29/2021
|
||||
* @author toric
|
||||
*/
|
||||
public class Scores{
|
||||
private int[] list;
|
||||
private int count=0;
|
||||
|
||||
/**
|
||||
* default constructor
|
||||
*/
|
||||
public Scores(){
|
||||
list = new int[50];
|
||||
}
|
||||
|
||||
/**
|
||||
* constructs starting array based off of passed size.
|
||||
* @param initSize size of inital array
|
||||
*/
|
||||
public Scores(int initSize){
|
||||
list = new int[initSize];
|
||||
}
|
||||
|
||||
/**
|
||||
* returns number of values of scores.
|
||||
* @return size of list
|
||||
*/
|
||||
public int size(){return count;}
|
||||
|
||||
/**
|
||||
* returns true if empty
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isEmpty(){
|
||||
if(count==0){
|
||||
return true;
|
||||
}
|
||||
else{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* clears contents of array
|
||||
*/
|
||||
public void clear(){count = 0;} //we dont need to delete the actual contents, just mark them as garbage.
|
||||
|
||||
/**
|
||||
*
|
||||
* @param object number you want to know frequency of
|
||||
* @return number of times object occurs
|
||||
*/
|
||||
public int getFrequencyOf(int object){
|
||||
int frequency=0;
|
||||
for(int i=0; i<count; i++){
|
||||
if(list[i]==object){frequency++;}
|
||||
}
|
||||
return frequency;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param object number you want to know whether the list contains.
|
||||
* @return boolean true if object is in the list.
|
||||
*/
|
||||
public boolean contains(int object){
|
||||
for(int i=0; i<count; i++){
|
||||
if(list[i]==object){return true;}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* adds object to the end of the list.
|
||||
* @param object the number to add to the end.
|
||||
*/
|
||||
public void add(int object){
|
||||
if(count==list.length){
|
||||
int tmp[] = new int[count*2];
|
||||
for(int i=0; i<count; i++){
|
||||
tmp[i]=list[i];
|
||||
}
|
||||
list=tmp;
|
||||
}
|
||||
list[count]=object; //since java has 0-based array, count is also the next free index.
|
||||
count++;
|
||||
}
|
||||
|
||||
/**
|
||||
* removes item at index, shifting remaining items to the left. returns the item removed
|
||||
* @param int index index of item to remove
|
||||
*/
|
||||
private int removeIndex(int index){ //not sure if we are suppoded to do this, but it deduplicates code.
|
||||
int tmp = list[index];
|
||||
if(index<count){
|
||||
for(int i=index; i<count; i++){
|
||||
list[i]=list[i+1]; //shift everything to the left.
|
||||
}
|
||||
count--;
|
||||
return tmp;
|
||||
}
|
||||
else{
|
||||
throw new ArrayIndexOutOfBoundsException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* removes the first occurrence of object. shifts the remaining values to cover the gap.
|
||||
* @param object to remove the first occurrence of.
|
||||
*/
|
||||
public void remove(int object){
|
||||
int index=-1;
|
||||
for(int i=0; i<count; i++){
|
||||
if(list[i]==object){
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(index==-1){ //return null if there is no match
|
||||
return;
|
||||
}
|
||||
removeIndex(index);
|
||||
}
|
||||
|
||||
/**
|
||||
* removes a random value from the list. shifts remaining values to cover the gap
|
||||
* returns null if list is empty
|
||||
*/
|
||||
public void remove(){
|
||||
if(count==0){
|
||||
return;
|
||||
}
|
||||
java.util.Random rand = new java.util.Random();
|
||||
|
||||
removeIndex(rand.nextInt(count)); // the upper bound of the nextInt function is exclusive, but since java has 0-based arrays, the max index is 1 less than count.
|
||||
}
|
||||
|
||||
/**
|
||||
* gets value at i
|
||||
* @param i index of value to get
|
||||
* @return value at index i
|
||||
*/
|
||||
public int get(int i){
|
||||
if(i<count){
|
||||
return list[i];
|
||||
}
|
||||
else{
|
||||
throw new ArrayIndexOutOfBoundsException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param o object to compare to
|
||||
* @return true of objects are equal
|
||||
*/
|
||||
public boolean equals(Object o){
|
||||
if (!(o instanceof Scores)){
|
||||
return false;
|
||||
}
|
||||
Scores s = (Scores)o;
|
||||
//easy to check, makes sure we dont waste time doing more in depth check if we dont need to. also saves us from an indexoutofbounds.
|
||||
if(!(s.count==count)){
|
||||
return false;
|
||||
}
|
||||
|
||||
for(int i=0; i<count; i++){
|
||||
if(!(list[i]==s.list[i])){
|
||||
return false; //this has the happy accident of only iterating the list untill we find one inequality.
|
||||
}
|
||||
}
|
||||
//if we get all the way through without discovering an inequality, they must be equal.
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return string representing contents of object.
|
||||
*/
|
||||
public String toString(){
|
||||
String contents = "";
|
||||
for(int i=0; i<count; i++){
|
||||
contents =contents+":"+list[i];
|
||||
}
|
||||
|
||||
return getClass().getName()+'@'+count+':'+contents;
|
||||
}
|
||||
}
|
3
Lab103-VenbergGE/manifest.mf
Normal file
3
Lab103-VenbergGE/manifest.mf
Normal file
|
@ -0,0 +1,3 @@
|
|||
Manifest-Version: 1.0
|
||||
X-COMMENT: Main-Class will be added automatically by build
|
||||
|
207
Lab103-VenbergGE/src/ArrayBag.java
Normal file
207
Lab103-VenbergGE/src/ArrayBag.java
Normal file
|
@ -0,0 +1,207 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @version 02/10/2021
|
||||
* @author toric
|
||||
*/
|
||||
public class ArrayBag<T> implements Bag<T>{
|
||||
private T[] list;
|
||||
private int count=0;
|
||||
|
||||
/**
|
||||
* default constructor
|
||||
*/
|
||||
public ArrayBag(){
|
||||
list = (T[]) new Object[50];
|
||||
}
|
||||
|
||||
/**
|
||||
* constructs starting array based off of passed size.
|
||||
* @param initSize size of inital array
|
||||
*/
|
||||
public ArrayBag(int initSize){
|
||||
list = (T[]) new Object[initSize];
|
||||
}
|
||||
|
||||
/**
|
||||
* returns number of values of scores.
|
||||
* @return size of list
|
||||
*/
|
||||
public int size(){return count;}
|
||||
|
||||
/**
|
||||
* returns true if empty
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isEmpty(){
|
||||
if(count==0){
|
||||
return true;
|
||||
}
|
||||
else{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* clears contents of array
|
||||
*/
|
||||
public void clear(){count = 0;} //we dont need to delete the actual contents, just mark them as garbage.
|
||||
|
||||
/**
|
||||
*
|
||||
* @param object number you want to know frequency of
|
||||
* @return number of times object occurs
|
||||
*/
|
||||
public int getFrequencyOf(T object){
|
||||
int frequency=0;
|
||||
for(int i=0; i<count; i++){
|
||||
if(list[i]==object){frequency++;}
|
||||
}
|
||||
return frequency;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param object number you want to know whether the list contains.
|
||||
* @return boolean true if object is in the list.
|
||||
*/
|
||||
public boolean contains(T object){
|
||||
for(int i=0; i<count; i++){
|
||||
if(list[i]==object){return true;}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* adds object to the end of the list.
|
||||
* @param object the number to add to the end.
|
||||
*/
|
||||
public void add(T object){
|
||||
if(count==list.length){
|
||||
T tmp[] = (T[]) new Object[count*2];
|
||||
for(int i=0; i<count; i++){
|
||||
tmp[i]=list[i];
|
||||
}
|
||||
list=tmp;
|
||||
}
|
||||
list[count]=object; //since java has 0-based array, count is also the next free index.
|
||||
count++;
|
||||
}
|
||||
|
||||
/**
|
||||
* removes item at index, shifting remaining items to the left. returns the item removed
|
||||
* @param int index index of item to remove
|
||||
*/
|
||||
private T removeIndex(int index){ //not sure if we are suppoded to do this, but it deduplicates code.
|
||||
T tmp = list[index];
|
||||
if(index<count){
|
||||
for(int i=index; i<count-1; i++){
|
||||
list[i]=list[i+1]; //shift everything to the left.
|
||||
}
|
||||
count--;
|
||||
//given the object has been removed from the list, I dont think we have to worry about encapsulation.
|
||||
return tmp;
|
||||
}
|
||||
else{
|
||||
throw new ArrayIndexOutOfBoundsException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* removes the first occurrence of object. shifts the remaining values to cover the gap.
|
||||
* returns null if list is empty
|
||||
* @param object to remove the first occurrence of.
|
||||
*/
|
||||
public T remove(T object){
|
||||
int index=-1;
|
||||
for(int i=0; i<count; i++){
|
||||
if(list[i].equals(object)){
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(index==-1){ //return null if there is no match
|
||||
return null;
|
||||
}
|
||||
return removeIndex(index);
|
||||
}
|
||||
|
||||
/**
|
||||
* removes a random value from the list. shifts remaining values to cover the gap
|
||||
* returns null if list is empty
|
||||
*/
|
||||
public T remove(){
|
||||
if(count==0){
|
||||
return null;
|
||||
}
|
||||
java.util.Random rand = new java.util.Random();
|
||||
|
||||
return removeIndex(rand.nextInt(count)); // the upper bound of the nextInt function is exclusive, but since java has 0-based arrays, the max index is 1 less than count.
|
||||
}
|
||||
|
||||
/**
|
||||
* gets value at i
|
||||
* @param i index of value to get
|
||||
* @return value at index i
|
||||
*/
|
||||
public T get(int i){
|
||||
if(i<count){
|
||||
return list[i];
|
||||
}
|
||||
else{
|
||||
throw new ArrayIndexOutOfBoundsException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param o object to compare to
|
||||
* @return true of objects are equal
|
||||
*/
|
||||
public boolean equals(Object o){
|
||||
if (!(o instanceof ArrayBag)){
|
||||
return false;
|
||||
}
|
||||
ArrayBag s = (ArrayBag)o;
|
||||
//easy to check, makes sure we dont waste time doing more in depth check if we dont need to. also saves us from an indexoutofbounds.
|
||||
if(!(s.count==count)){
|
||||
return false;
|
||||
}
|
||||
|
||||
for(int i=0; i<count; i++){
|
||||
if(!(list[i].equals(s.list[i]))){
|
||||
return false; //this has the happy accident of only iterating the list untill we find one inequality.
|
||||
}
|
||||
}
|
||||
//if we get all the way through without discovering an inequality, they must be equal.
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return string representing contents of object.
|
||||
*/
|
||||
public String toString(){
|
||||
String contents = "";
|
||||
for(int i=0; i<count; i++){
|
||||
contents =contents+":"+list[i].toString();
|
||||
}
|
||||
|
||||
return getClass().getName()+'@'+count+':'+contents;
|
||||
}
|
||||
}
|
45
Lab103-VenbergGE/src/Bag.java
Normal file
45
Lab103-VenbergGE/src/Bag.java
Normal file
|
@ -0,0 +1,45 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
*@date 02/10/2021
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public interface Bag<E> {
|
||||
|
||||
public int size();
|
||||
|
||||
public boolean isEmpty();
|
||||
|
||||
public void clear();
|
||||
|
||||
public int getFrequencyOf(E e);
|
||||
|
||||
public boolean contains(E e);
|
||||
|
||||
public void add(E e);
|
||||
|
||||
public E remove(E e);
|
||||
|
||||
public E remove();
|
||||
|
||||
public E get(int i);
|
||||
|
||||
public String toString();
|
||||
|
||||
public boolean equals(Object o);
|
||||
}
|
88
Lab103-VenbergGE/src/Client.java
Normal file
88
Lab103-VenbergGE/src/Client.java
Normal file
|
@ -0,0 +1,88 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
*@date 02/10/2021
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public class Client {
|
||||
public static void main(String args[]){
|
||||
ArrayBag mensTeam = new ArrayBag(2);
|
||||
|
||||
//I have no clue how football works, so Im just using dumb values.
|
||||
mensTeam.add(new Player("name1", "position1", 1));
|
||||
mensTeam.add(new Player("name2", "position2", 2));
|
||||
mensTeam.add(new Player("name3", "position3", 3));
|
||||
mensTeam.add(new Player("name4", "position4", 4));
|
||||
mensTeam.add(new Player("name5", "position5", 5));
|
||||
mensTeam.add(new Player("name6", "position6", 6));
|
||||
mensTeam.add(new Player("name7", "position7", 7));
|
||||
mensTeam.add(new Player("name8", "position8", 8));
|
||||
|
||||
System.out.println(mensTeam.toString());
|
||||
|
||||
mensTeam.remove();
|
||||
|
||||
System.out.println(mensTeam.toString());
|
||||
|
||||
mensTeam.add(new Player("name9", "position9", 9));
|
||||
|
||||
System.out.println(mensTeam.toString());
|
||||
|
||||
mensTeam.remove(new Player("name9", "position9", 9));
|
||||
|
||||
System.out.println(mensTeam.toString());
|
||||
|
||||
ArrayBag courses = new ArrayBag(3);
|
||||
|
||||
courses.add("MATH 265");
|
||||
courses.add("CSCI 222");
|
||||
courses.add("CSCI 161");
|
||||
|
||||
System.out.println(courses.toString());
|
||||
|
||||
courses.remove();
|
||||
|
||||
System.out.println(courses.toString());
|
||||
|
||||
LinkedBag womensTeam = new LinkedBag();
|
||||
|
||||
//I have no clue how football works, so Im just using dumb values.
|
||||
womensTeam.add(new Player("name1", "position1", 1));
|
||||
womensTeam.add(new Player("name2", "position2", 2));
|
||||
womensTeam.add(new Player("name3", "position3", 3));
|
||||
womensTeam.add(new Player("name4", "position4", 4));
|
||||
womensTeam.add(new Player("name5", "position5", 5));
|
||||
womensTeam.add(new Player("name6", "position6", 6));
|
||||
womensTeam.add(new Player("name7", "position7", 7));
|
||||
womensTeam.add(new Player("name8", "position8", 8));
|
||||
|
||||
System.out.println(womensTeam.toString());
|
||||
|
||||
womensTeam.remove();
|
||||
|
||||
System.out.println(womensTeam.toString());
|
||||
|
||||
womensTeam.add(new Player("name9", "position9", 9));
|
||||
|
||||
System.out.println(womensTeam.toString());
|
||||
|
||||
womensTeam.remove(new Player("name9", "position9", 9));
|
||||
|
||||
System.out.println(womensTeam.toString());
|
||||
}
|
||||
}
|
247
Lab103-VenbergGE/src/LinkedBag.java
Normal file
247
Lab103-VenbergGE/src/LinkedBag.java
Normal file
|
@ -0,0 +1,247 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
*@date 02/10/2021
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public class LinkedBag<T> implements Bag<T> {
|
||||
|
||||
//dont need a count variable, linkedlist already takes care of that.
|
||||
private SinglyLinkedList list;
|
||||
|
||||
public LinkedBag(){
|
||||
list = new SinglyLinkedList<T>();
|
||||
}
|
||||
|
||||
public LinkedBag(int initSize){
|
||||
this();
|
||||
}
|
||||
/**
|
||||
*
|
||||
* @return size of list
|
||||
*/
|
||||
public int size(){return list.size();}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return true if list is empty
|
||||
*/
|
||||
public boolean isEmpty(){return list.isEmpty();}
|
||||
|
||||
/**
|
||||
* emptys list of all entries
|
||||
*/
|
||||
public void clear(){
|
||||
for(int i=0; i<list.size(); i++){
|
||||
list.removeFirst();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Ok, so this next bit gets MESSY. I feel like we should just add a method or two to the singlyLinkedList class.
|
||||
The class that my copy of the book has only contains methods for acessing/adding to the list at the tail or head,
|
||||
and only lets me remove from the head. This means that any object not at the head or tail is COMPLETELY INACESSABLE
|
||||
to me without modifying the list. So, from here on out, I will be using a second temporary stack and move items from
|
||||
one or the other, reading/modifying each item as its tranferred. This is wildly inneffiennt compared
|
||||
to if the linkedlist class just let me traverse the list, but the assignment says not to modify the list, sooo...
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @param object object to search for
|
||||
* @return number of times object appears in list.
|
||||
*/
|
||||
public int getFrequencyOf(T object){
|
||||
T entry; //dont want to re-initalize this every loop.
|
||||
SinglyLinkedList tmp = new SinglyLinkedList<T>();
|
||||
int freqency=0;
|
||||
|
||||
int size = list.size(); //If you dont do this, list.size will shrink every loop, and you will only get through half the list as i grows and list.size shrinks.
|
||||
for(int i=0; i<size; i++){
|
||||
//not sure why I had to cast this, it should return T, but the complier seems to think its returning Object.
|
||||
entry = (T) list.removeFirst();
|
||||
if(entry.equals(object)){
|
||||
freqency++;
|
||||
}
|
||||
//if we did addFirst, it would result in tmp being an inverted version of list.
|
||||
tmp.addLast(entry);
|
||||
}
|
||||
//we have shifted all of list to tmp.
|
||||
list = tmp;
|
||||
return freqency;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param object object to search for
|
||||
* @return true if list contains at least one of object.
|
||||
*/
|
||||
public boolean contains(T object){
|
||||
/*
|
||||
so in arrayBag I used different methods for contains and frequency to save time after finding a match in contains.
|
||||
Why not in this method? because I cant stop halfway through. I am destructivly reading the list and reconstructing it in tmp,
|
||||
meaning I cant stop halfway through even if I do find a match. only thing I would be saving would be the comparison.
|
||||
*/
|
||||
return getFrequencyOf(object)>0;
|
||||
}
|
||||
|
||||
public void add(T object){
|
||||
list.addFirst(object);
|
||||
}
|
||||
|
||||
/**
|
||||
* deletes the first instance of object from the list.
|
||||
* @param object object to delete
|
||||
* @return object that was deleted
|
||||
*/
|
||||
public T remove(T object){
|
||||
T entry; //dont want to re-initalize this every loop.
|
||||
T result=null; //cant have return ending our loop early.
|
||||
SinglyLinkedList tmp = new SinglyLinkedList<T>();
|
||||
|
||||
int size = list.size(); //If you dont do this, list.size will shrink every loop, and you will only get through half the list as i grows and list.size shrinks.
|
||||
for(int i=0; i<size; i++){
|
||||
entry = (T) list.removeFirst();
|
||||
//if the object we want to delete is found, we record it and break out of the loop BEFORE we put it on the new stack.
|
||||
if (entry.equals(object)){
|
||||
result = entry;
|
||||
break;
|
||||
}
|
||||
tmp.addLast(entry);
|
||||
}
|
||||
|
||||
//finish the juggle the loop SHOULD do nothing if list is empty by now.
|
||||
size = list.size(); //If you dont do this, list.size will shrink every loop, and you will only get through half the list as i grows and list.size shrinks.
|
||||
for(int i=0; i<size; i++){
|
||||
tmp.addLast(list.removeFirst());
|
||||
}
|
||||
list=tmp;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* removes a random object from the list
|
||||
* @return object that was deleted
|
||||
*/
|
||||
public T remove(){
|
||||
T result=null; //cant have return ending our loop early.
|
||||
SinglyLinkedList tmp = new SinglyLinkedList<T>();
|
||||
|
||||
java.util.Random rand = new java.util.Random();
|
||||
|
||||
int indexToRemove = rand.nextInt(list.size());
|
||||
|
||||
//juggle a bit before we delete
|
||||
for(int i=0; i<indexToRemove; i++){
|
||||
tmp.addLast(list.removeFirst());
|
||||
}
|
||||
|
||||
//delete
|
||||
result=(T) list.removeFirst();
|
||||
|
||||
//finish the juggle...
|
||||
for(int i=0; i<list.size(); i++){
|
||||
tmp.addLast(list.removeFirst());
|
||||
}
|
||||
|
||||
list=tmp;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* retrieves an item by its index. more expensive than you think!
|
||||
* @param item index of item to retrieve
|
||||
* @return retrieved item
|
||||
*/
|
||||
public T get(int item){
|
||||
T result = null;
|
||||
SinglyLinkedList tmp = new SinglyLinkedList<T>();
|
||||
|
||||
//juggle till we get to where we need to be
|
||||
for(int i=0; i<item; i++){
|
||||
tmp.addLast(list.removeFirst());
|
||||
}
|
||||
|
||||
//record
|
||||
result=(T) list.removeFirst();
|
||||
tmp.addLast(result);
|
||||
|
||||
//finish the juggle...
|
||||
for(int i=0; i<list.size(); i++){
|
||||
tmp.addLast(list.removeFirst());
|
||||
}
|
||||
|
||||
list=tmp;//at this point Im just thankfull we can do this instead of having to juggle BACK!
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return contents of object as string
|
||||
*/
|
||||
public String toString(){
|
||||
String contents ="";
|
||||
T entry;
|
||||
SinglyLinkedList tmp = new SinglyLinkedList<T>();
|
||||
//the first record of juggling dates to between 1994 and 1781 BC, with the egyptians!
|
||||
int size = list.size(); //If you dont do this, list.size will shrink every loop, and you will only get through half the list as i grows and list.size shrinks.
|
||||
for(int i=0; i<size; i++){
|
||||
entry = (T) list.removeFirst();
|
||||
contents = contents+':'+entry.toString();
|
||||
tmp.addLast(entry);
|
||||
}
|
||||
list=tmp;
|
||||
return getClass().getName()+'@'+list.size()+':'+contents;
|
||||
}
|
||||
|
||||
/**
|
||||
* compares with another object.
|
||||
* @param o object to compare with
|
||||
* @return true if objects are identical
|
||||
*/
|
||||
public boolean equals(Object o){
|
||||
if (!(o instanceof LinkedBag)){return false;}
|
||||
|
||||
LinkedBag l = (LinkedBag) o;
|
||||
if(l.size()!=list.size()){return false;}
|
||||
|
||||
SinglyLinkedList tmp1 = new SinglyLinkedList<T>();
|
||||
SinglyLinkedList tmp2 = new SinglyLinkedList<T>();
|
||||
boolean result = true;
|
||||
T entry1, entry2;//need two of these, as I dont want to destroy the list passed to me, either.
|
||||
|
||||
/*
|
||||
In ancient China, juggling was an art performed by some warriors.
|
||||
One such warrior was Xiong Yiliao, whose juggling of nine balls
|
||||
in front of troops on a battlefield reportedly caused the opposing troops to flee without fighting,
|
||||
resulting in a complete victory. (from wikipedia)
|
||||
*/
|
||||
int size = list.size(); //If you dont do this, list.size will shrink every loop, and you will only get through half the list as i grows and list.size shrinks.
|
||||
for(int i=0; i<size; i++){
|
||||
entry1=(T) list.removeFirst();
|
||||
entry2=(T) l.list.removeFirst();
|
||||
//dont want to return with list items still 'in the air' (ive taken this juggling metaphor to far! help!)
|
||||
if(!entry1.equals(entry2)){result = false;}
|
||||
tmp1.addLast(entry1);
|
||||
tmp2.addLast(entry2);
|
||||
}
|
||||
list=tmp1;
|
||||
l.list=tmp2;
|
||||
return result;
|
||||
}
|
||||
}
|
90
Lab103-VenbergGE/src/Player.java
Normal file
90
Lab103-VenbergGE/src/Player.java
Normal file
|
@ -0,0 +1,90 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
*@date 02/10/2021
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public class Player {
|
||||
private String name;
|
||||
private String positionPlayed; //I think positionPlayed should be a string? I know absolutly nothing about football.
|
||||
int jersyNumber;
|
||||
|
||||
public Player(String name, String positionPlayed, int jersyNumber){
|
||||
this.name = name;
|
||||
this.positionPlayed = positionPlayed;
|
||||
this.jersyNumber = jersyNumber;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* @return name of player
|
||||
*/
|
||||
public String getName(){return name;}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return positonPlayed of player
|
||||
*/
|
||||
public String getPositionPlayed(){return positionPlayed;}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return jersyNumber of player
|
||||
*/
|
||||
public int getJersyNumber(){return jersyNumber;}
|
||||
|
||||
/**
|
||||
* sets name of player
|
||||
* @param name
|
||||
*/
|
||||
public void setName(String name){this.name=name;}
|
||||
|
||||
/**
|
||||
* sets positionPlayed of player
|
||||
* @param positionPlayed
|
||||
*/
|
||||
public void setPositionPlayed(String positionPlayed){this.positionPlayed=positionPlayed;}
|
||||
|
||||
/**
|
||||
* sets jersyNumber of player
|
||||
* @param jersyNumber
|
||||
*/
|
||||
public void setJersyNumber(int jersyNumber){this.jersyNumber=jersyNumber;}
|
||||
|
||||
/**
|
||||
* outputs contents of object as string
|
||||
* @return String
|
||||
*/
|
||||
public String toString(){
|
||||
return getClass().getName()+'@'+':'+name+':'+positionPlayed+':'+jersyNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
* compares with another object
|
||||
* @param o object to compare to
|
||||
* @return true if objects are identical.
|
||||
*/
|
||||
public boolean equals(Object o){
|
||||
if (!(o instanceof Player)){return false;}
|
||||
|
||||
Player p = (Player) o;
|
||||
|
||||
return name.equals(p.name)&&
|
||||
positionPlayed.equals(p.positionPlayed)&&
|
||||
jersyNumber==p.jersyNumber;
|
||||
}
|
||||
}
|
78
Lab103-VenbergGE/src/SinglyLinkedList.java
Normal file
78
Lab103-VenbergGE/src/SinglyLinkedList.java
Normal file
|
@ -0,0 +1,78 @@
|
|||
/**
|
||||
*SinglyLinkedListClass
|
||||
* Code Fragments 3.14, 3.15
|
||||
* from
|
||||
* Data Structures & Algorithms, 6th edition
|
||||
* by Michael T. Goodrich, Roberto Tamassia & Michael H. Goldwasser
|
||||
* Wiley 2014
|
||||
* Transcribed by
|
||||
* @author Gabe Venberg
|
||||
*/
|
||||
public class SinglyLinkedList<E> {
|
||||
|
||||
private static class Node<E> {
|
||||
private E element; //refrence to element stored at this node
|
||||
private Node<E> next; //refrence to subsequent node of list
|
||||
|
||||
public Node(E e, Node<E> n){
|
||||
element = e;
|
||||
next = n;
|
||||
}
|
||||
|
||||
public E getElement() {return element;}
|
||||
|
||||
public Node<E> getNext() {return next;}
|
||||
|
||||
public void setNext(Node<E> n) {next = n;}
|
||||
}
|
||||
|
||||
//instance variables of SinglyLinkedList
|
||||
private Node<E> head = null;//head node of list
|
||||
private Node<E> tail = null;//last node of list
|
||||
private int size = 0;//number of nodes in list
|
||||
|
||||
public SinglyLinkedList(){}//constructs an initaly empty list
|
||||
|
||||
//access methods
|
||||
public int size() {return size;}
|
||||
|
||||
public boolean isEmpty() {return size == 0;}
|
||||
|
||||
public E first(){//returns but does not remove the first element
|
||||
if (size == 0) {return null;} //special case
|
||||
return head.getElement();
|
||||
}
|
||||
|
||||
public E last(){//returns but does not remove last elemnt
|
||||
if (size ==0) {return null;}//special case
|
||||
return tail.getElement();
|
||||
}
|
||||
|
||||
//update methods
|
||||
public void addFirst(E e){//adds element e to the front of the list
|
||||
head = new Node<>(e, head);//create and link a new node
|
||||
if (size == 0) {tail = head;}//special case, head becomes tail also
|
||||
size++;
|
||||
}
|
||||
|
||||
public void addLast(E e){//adds element to end of list
|
||||
Node<E> newest = new Node<>(e, null);//create and link a new node
|
||||
if(size == 0){//special case, previously empty list
|
||||
head = newest;
|
||||
}
|
||||
else{
|
||||
tail.setNext(newest);//new node after existing tail
|
||||
}
|
||||
tail = newest;//new node becomes tail
|
||||
size++;
|
||||
}
|
||||
|
||||
public E removeFirst(){//removes and returns the first element
|
||||
if(size == 0){return null;}//nothing to remove
|
||||
E answer = head.getElement();
|
||||
head = head.getNext();//will become null if list had only one node.
|
||||
size--;
|
||||
if(size==0){tail = null;}// special case as list is now empty
|
||||
return answer;
|
||||
}
|
||||
}
|
3
Lab104-VenbergGE/manifest.mf
Normal file
3
Lab104-VenbergGE/manifest.mf
Normal file
|
@ -0,0 +1,3 @@
|
|||
Manifest-Version: 1.0
|
||||
X-COMMENT: Main-Class will be added automatically by build
|
||||
|
89
Lab104-VenbergGE/src/Client.java
Normal file
89
Lab104-VenbergGE/src/Client.java
Normal file
|
@ -0,0 +1,89 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import javax.swing.JOptionPane;
|
||||
import java.util.Scanner;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
public class Client {
|
||||
public static String fileToString(String filePath) throws FileNotFoundException{//helper function.
|
||||
File file = new File(filePath);
|
||||
Scanner input = new Scanner(file);
|
||||
String output = "";
|
||||
while(input.hasNextLine()){
|
||||
output = output +'\n'+input.nextLine();
|
||||
}
|
||||
return output;
|
||||
}
|
||||
public static void main(String[] args) throws FileNotFoundException{
|
||||
String[] functions = {"Harmonic", "sum", "find"};
|
||||
|
||||
String input;
|
||||
while(true){
|
||||
input = (String) JOptionPane.showInputDialog(null, "What function would you like to test?",
|
||||
"Testing", JOptionPane.QUESTION_MESSAGE, null, functions, functions[1]);
|
||||
|
||||
switch(input){
|
||||
case "Harmonic":
|
||||
input = (String) JOptionPane.showInputDialog(null, "what harmonic number do you want?", "Harmonic", 0);
|
||||
double hResult =Recursion.harmonic(Integer.parseInt(input));
|
||||
JOptionPane.showMessageDialog(null, "the result is "+hResult);
|
||||
System.out.println("tested harmonic, input was "+input+" and result was "+hResult);
|
||||
break;
|
||||
case "sum":
|
||||
while(true){ //the loop is just to provide the option of continuing if you want
|
||||
input = (String) JOptionPane.showInputDialog(null, "enter the file containing the array", "Sum", 0);
|
||||
int sResult;
|
||||
try{
|
||||
sResult = Recursion.sum(new File(input));
|
||||
JOptionPane.showMessageDialog(null, sResult);
|
||||
System.out.println("testing sum, user entered "+input+" and file contained "+fileToString(input)+". result was "+sResult);
|
||||
}
|
||||
catch(FileNotFoundException e){
|
||||
int reply = JOptionPane.showConfirmDialog(null, "file does not exit", "continue?", 0);
|
||||
if(reply == 0){
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case "find": //you didnt say anything about how this loop should behave. Also, you spesifically said the find method has a void return type, so I cant use the dialog box for output.
|
||||
input = (String) JOptionPane.showInputDialog(null, "Enter the directory you want to search", "Find", 0);
|
||||
String input2 = JOptionPane.showInputDialog(null, "enter your seach term", 0);
|
||||
try{
|
||||
Recursion.find(input, input2);
|
||||
System.out.println("tested find, start directory was "+input+" and search term was "+input2);
|
||||
}
|
||||
catch (IOException ex) {
|
||||
JOptionPane.showMessageDialog(null, "cant find that file");
|
||||
}
|
||||
break;
|
||||
}
|
||||
int doAgain = JOptionPane.showConfirmDialog(null, null, "continue?", 0);
|
||||
if(doAgain==1){break;}
|
||||
}
|
||||
}
|
||||
}
|
119
Lab104-VenbergGE/src/Recursion.java
Normal file
119
Lab104-VenbergGE/src/Recursion.java
Normal file
|
@ -0,0 +1,119 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.util.Scanner;
|
||||
import java.lang.StringBuilder;
|
||||
|
||||
public class Recursion {
|
||||
|
||||
public static int sum(File file) throws FileNotFoundException{
|
||||
Scanner input = new Scanner(file);
|
||||
|
||||
int fileLength = 0;
|
||||
//wont be using the singly linked list class from last time, as it was really incomplete. Ill hack this together with a proper array.
|
||||
while(input.hasNext()==true){
|
||||
if(input.hasNextInt()){
|
||||
fileLength ++;
|
||||
input.nextInt();
|
||||
}
|
||||
else{
|
||||
input.next();
|
||||
}
|
||||
}
|
||||
input.close();
|
||||
|
||||
input = new Scanner(file); //resetting the scanner.
|
||||
|
||||
int[] product = new int[fileLength];
|
||||
|
||||
for(int i=0; i<product.length; i++){
|
||||
product[i]=input.nextInt();
|
||||
}
|
||||
|
||||
return sumCalc(product);
|
||||
}
|
||||
|
||||
public static double harmonic(double n){
|
||||
if(n<=0){
|
||||
throw new IllegalArgumentException("input must be > 1");
|
||||
}
|
||||
else if(n==1){
|
||||
return 1;
|
||||
}
|
||||
else{
|
||||
return (1.0/n)+harmonic(n-1.0);
|
||||
}
|
||||
}
|
||||
|
||||
//splitting up the code here, was to implement the sum by itself.
|
||||
|
||||
private static int sumCalc(int a[]){
|
||||
/* It can actually be realy easy to check if a number is a power of 2 thanks to binary.
|
||||
all powers of 2 take the form of 1 followed by a n 0's. If we sub 1 from this number,
|
||||
it becomes 0 followed by n 0's. Something like this (for the number 16)
|
||||
10000 (16)
|
||||
01111 (15)
|
||||
So taking a bitwise and will give us 0. (note that this only works with counting numbers, so no 0!)
|
||||
|
||||
Note that I dont have a proof that only powers of 2 do this, just a strong
|
||||
suspicion and a brute force search of the first million integers in python.
|
||||
I may have gotten a bit distracted...
|
||||
*/
|
||||
if((a.length&(a.length-1))==0){
|
||||
if(a.length==1){return a[0];}
|
||||
else{
|
||||
int[] tmp = new int[a.length/2];
|
||||
for(int i=0; i<tmp.length; i++){
|
||||
tmp[i] = a[2*i]+a[2*i+1];
|
||||
}
|
||||
return sumCalc(tmp);
|
||||
}
|
||||
}
|
||||
else{
|
||||
throw new IllegalArgumentException("input must be a power of 2.");
|
||||
}
|
||||
}
|
||||
|
||||
public static void find(String startPath, String filename) throws IOException{
|
||||
/*so, I spent an hour trying to write a (O(n!)(I think)) recursive substring search function,
|
||||
rather than a find [startPath] -name 'filename' ... I can *totaly* read...
|
||||
*/
|
||||
|
||||
File startFile = new File(startPath);
|
||||
|
||||
if(!startFile.isDirectory()){ //base case is a non-directory
|
||||
if(startFile.getName().equals(filename)){
|
||||
System.out.println(startFile.getCanonicalPath());
|
||||
}
|
||||
}
|
||||
else{
|
||||
String[] nextFiles = startFile.list(); //array of files to try next
|
||||
|
||||
for(int i=0; i<nextFiles.length; i++){
|
||||
find(nextFiles[i], filename);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
3
Lab105-VenbergGE/manifest.mf
Normal file
3
Lab105-VenbergGE/manifest.mf
Normal file
|
@ -0,0 +1,3 @@
|
|||
Manifest-Version: 1.0
|
||||
X-COMMENT: Main-Class will be added automatically by build
|
||||
|
114
Lab105-VenbergGE/src/ASCIITable.java
Normal file
114
Lab105-VenbergGE/src/ASCIITable.java
Normal file
|
@ -0,0 +1,114 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
*utility library for nicely formatted ascii tables.
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public class ASCIITable {
|
||||
|
||||
/**
|
||||
* render 2D array data into a table. the top level array is an array of rows.
|
||||
* @param data 2D array of data. Must have toString.
|
||||
* @param padding space padding on either side of data.
|
||||
* @return String containing table.
|
||||
*/
|
||||
public static String render(Object data[][], int padding){
|
||||
int colWidth = calcColumnWidth(data);
|
||||
int rows = calcNoRows(data);
|
||||
String horizontalSpacer = assembleHorizontalSpacers(colWidth, padding, rows);
|
||||
/*ok, so each cell will have the colwidth for the data, then padding for padding,
|
||||
* then a | at the end. (plus 1 at the begginning of the table.
|
||||
there will be 2 rows for each row of data (horizontal sep) plus a horizontal sep
|
||||
at the end.
|
||||
*/
|
||||
String string = "";
|
||||
//got everything set up, build the table row by row.
|
||||
for(int i=0; i<data.length; i++){
|
||||
string = string+horizontalSpacer+"\n";
|
||||
string = string+dataString(colWidth, padding, data[i])+'\n';
|
||||
}
|
||||
string = string+horizontalSpacer;
|
||||
return string;
|
||||
}
|
||||
|
||||
/**
|
||||
* calculates the maximum number of entries the rows in the data set have
|
||||
* @param data 2D array of data
|
||||
* @return needed number of rows in the final table.
|
||||
*/
|
||||
private static int calcNoRows(Object data[][]){
|
||||
int rows = 0;
|
||||
for(int i=0; i<data.length; i++){
|
||||
rows = Math.max(rows, data[i].length);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
/**
|
||||
* calculates the needed column width for a data array without padding
|
||||
* @param data the array of data
|
||||
* @return an integer representing the needed width of the column
|
||||
*/
|
||||
private static int calcColumnWidth(Object data[][]){
|
||||
int maxWidth = 0;
|
||||
for(int i=0; i<data.length; i++){
|
||||
for(int j=0; j<data[i].length; j++){
|
||||
maxWidth = Math.max(maxWidth, data[i][j].toString().length());
|
||||
}
|
||||
}
|
||||
return maxWidth;
|
||||
}
|
||||
|
||||
/**
|
||||
* gives the horizontal spacer needed for the table
|
||||
* @param colWidth width of each column;
|
||||
* @param padding padding on each side of data.
|
||||
* @param noOfCols number of columns;
|
||||
* @return a string suitable to use as the horizontal spacer for the table.
|
||||
*/
|
||||
private static String assembleHorizontalSpacers(int colWidth, int padding, int noOfCols){
|
||||
String string = "+";
|
||||
for(int i=0; i<noOfCols; i++){
|
||||
for(int j=0; j<colWidth+2*padding; j++){
|
||||
string = string+'-';
|
||||
}
|
||||
string = string+'+';
|
||||
}
|
||||
return string;
|
||||
}
|
||||
|
||||
/**
|
||||
* takes a single row of the data array and returns a row. Make sure your colWidth is accurate.
|
||||
* @param colWidth width of each column
|
||||
* @param data 1D array of data to print
|
||||
* @return a string containing the data
|
||||
*/
|
||||
private static String dataString(int colWidth, int padding, Object data[]){
|
||||
String string ="|";
|
||||
//for each entry in the row
|
||||
for(int i=0; i<data.length; i++){
|
||||
//only calc this once.
|
||||
int length=data[i].toString().length();
|
||||
// front padding. Also, I wish java had string multiplication.
|
||||
for(int p=0; p<padding+(colWidth-length); p++){string = string+" ";}
|
||||
string = string+data[i].toString();
|
||||
for(int p=0; p<padding; p++){string = string+" ";}
|
||||
string = string+"|";
|
||||
}
|
||||
return string;
|
||||
}
|
||||
}
|
88
Lab105-VenbergGE/src/ArrayList.java
Normal file
88
Lab105-VenbergGE/src/ArrayList.java
Normal file
|
@ -0,0 +1,88 @@
|
|||
/*
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragments 7.2-7.5
|
||||
*
|
||||
* An implementation of the ArrayList class
|
||||
* */
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public class ArrayList<E> implements List<E> {
|
||||
//instance variables
|
||||
public static final int CAPACITY = 16; //default array capacity
|
||||
private E[] data; //generic array used for storage
|
||||
private int size = 0; //current number of elements
|
||||
|
||||
//constructors
|
||||
/**constructs the list with default capacity*/
|
||||
public ArrayList(){this(CAPACITY);}
|
||||
/**constructs the list with given capacity*/
|
||||
public ArrayList(int capacity){
|
||||
data = (E[]) new Object[capacity];
|
||||
}
|
||||
|
||||
//public methods
|
||||
/**Returns the number of elements int eh array list*/
|
||||
public int size(){return size;}
|
||||
/**returns whether the array list is empty*/
|
||||
public boolean isEmpty(){return size==0;}
|
||||
|
||||
/** returns but does not remove the element at index i*/
|
||||
public E get(int i) throws IndexOutOfBoundsException{
|
||||
checkIndex(i, size);
|
||||
return data[i];
|
||||
}
|
||||
|
||||
/**Replaces the element at index i with e, and returns the replaced element*/
|
||||
public E set(int i, E e) throws IndexOutOfBoundsException {
|
||||
checkIndex(i, size);
|
||||
E temp = data[i];
|
||||
data[i]=e;
|
||||
return temp;
|
||||
}
|
||||
|
||||
/** inserts element e to be at index i, shifting all subsequent elements later*/
|
||||
public void add(int i, E e) throws IndexOutOfBoundsException/*, IllegalStateException */{
|
||||
checkIndex(i, size+1);
|
||||
if(size==data.length){ //not enough capacity
|
||||
//throw new IllegalStateException("array is full");
|
||||
resize(2*data.length);//so double current capacity
|
||||
}
|
||||
for(int k=size-1; k>=i; k--){//start by shifting elements
|
||||
data[k+1]=data[k];
|
||||
}
|
||||
data[i]=e;//ready to place new element
|
||||
size++;
|
||||
}
|
||||
|
||||
/**removes and returns the element at index i, shifting subsequent elements earlier*/
|
||||
public E remove(int i) throws IndexOutOfBoundsException {
|
||||
checkIndex(i, size);
|
||||
E temp = data[i];
|
||||
for(int k=i; k<size-1;k++){//shift elements to fill hole
|
||||
data[k]=data[k+1];
|
||||
}
|
||||
data[size-1]=null; //help GC
|
||||
size--;
|
||||
return temp;
|
||||
}
|
||||
|
||||
//utility methods
|
||||
/**checks whether the given index is in the range [0, n-1]*/
|
||||
protected void checkIndex(int i, int n) throws IndexOutOfBoundsException{
|
||||
if(i<0||i>=n){
|
||||
throw new IndexOutOfBoundsException("illegal index: "+i+", size is "+size);
|
||||
}
|
||||
}
|
||||
|
||||
protected void resize(int capacity){
|
||||
E[] temp = (E[]) new Object[capacity];//safe cast, compiler may give warning
|
||||
for(int k=0; k<size; k++){
|
||||
temp[k]=data[k];
|
||||
}
|
||||
data=temp; //start using the new array
|
||||
}
|
||||
}
|
58
Lab105-VenbergGE/src/ArrayQueue.java
Normal file
58
Lab105-VenbergGE/src/ArrayQueue.java
Normal file
|
@ -0,0 +1,58 @@
|
|||
/*
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragment 6.10
|
||||
*
|
||||
* An implementation of the ArrayQueue class
|
||||
* */
|
||||
|
||||
/**
|
||||
*implementation of the queue ADT using a fixed-length array.
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public class ArrayQueue<E> implements Queue<E>{
|
||||
//instance variables
|
||||
private E[] data; //generic array used for storage
|
||||
private int f = 0; //index of the front element
|
||||
private int sz = 0; //current number of elements
|
||||
private static final int CAPACITY = 1000; //default capacity, book is missing this.
|
||||
|
||||
//constructors
|
||||
/** constructs queue with default capacity*/
|
||||
public ArrayQueue(){this(CAPACITY);}
|
||||
/**constructs queue with given capacity*/
|
||||
public ArrayQueue(int capacity){
|
||||
data = (E[]) new Object[capacity];
|
||||
}
|
||||
|
||||
//methods
|
||||
/** returns the number of elements in the queue*/
|
||||
public int size(){return sz;}
|
||||
|
||||
/** tests whether the queue is empty*/
|
||||
public boolean isEmpty(){return sz == 0;}
|
||||
|
||||
/**inserts an element at the rear of the queue*/
|
||||
public void enqueue(E e) throws IllegalStateException{
|
||||
if(sz==data.length){throw new IllegalStateException("queue is full");}
|
||||
int avail = (f+sz)%data.length; //use modular arithmatic
|
||||
data[avail]=e;
|
||||
sz++;
|
||||
}
|
||||
|
||||
/** returns but does not remove the first element in the queue or null if emtpy*/
|
||||
public E first(){
|
||||
if(isEmpty()){return null;}
|
||||
return data[f];
|
||||
}
|
||||
|
||||
/** removes and returns the first element of the queue or null if emtpy*/
|
||||
public E dequeue(){
|
||||
if(isEmpty()){return null;}
|
||||
E answer = data[f];
|
||||
data[f]=null; //dereference to help GC
|
||||
f=(f+1)%data.length;
|
||||
sz--;
|
||||
return answer;
|
||||
}
|
||||
}
|
55
Lab105-VenbergGE/src/ArrayStack.java
Normal file
55
Lab105-VenbergGE/src/ArrayStack.java
Normal file
|
@ -0,0 +1,55 @@
|
|||
/*
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragment 6.2
|
||||
*
|
||||
* An implementation of an ArrayStack class
|
||||
* */
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public class ArrayStack<E> implements Stack<E> {
|
||||
public static final int CAPACITY = 1000;//default capacity
|
||||
private E[] data; //generic array used for storage.
|
||||
private int t=-1; //index of the top element in the stack
|
||||
|
||||
|
||||
//im swiching the authors comments to javadoc style, for ease of use.
|
||||
|
||||
/**
|
||||
* constructs stack with default capacity
|
||||
*/
|
||||
public ArrayStack(){this(CAPACITY);}
|
||||
|
||||
/**
|
||||
* constructs stack with given capacity
|
||||
* @param capacity capacity to construct the stack with.
|
||||
*/
|
||||
public ArrayStack(int capacity){
|
||||
data = (E[]) new Object[capacity];
|
||||
}
|
||||
|
||||
public int size(){return (t+1);}
|
||||
|
||||
public boolean isEmpty(){return(t==-1);}
|
||||
|
||||
public void push(E e) throws IllegalStateException{
|
||||
if(size()==data.length){throw new IllegalStateException("Stack is full");}
|
||||
data[++t]=e; //increment t before storing a new item.
|
||||
}
|
||||
|
||||
public E top(){
|
||||
if(isEmpty()){return null;}
|
||||
return data[t];
|
||||
}
|
||||
|
||||
public E pop(){
|
||||
if(isEmpty()){return null;}
|
||||
E answer = data[t];
|
||||
data[t] = null; //dereference to help with garbage collection.
|
||||
t--;
|
||||
return answer;
|
||||
}
|
||||
}
|
121
Lab105-VenbergGE/src/Client.java
Normal file
121
Lab105-VenbergGE/src/Client.java
Normal file
|
@ -0,0 +1,121 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
|
||||
public class Client {
|
||||
public static void main(String args[]){
|
||||
|
||||
final int maxMag = 9;
|
||||
//maxMag-1 orders of magnitude (because we start from 10).
|
||||
//and 5 methods to try + col for iterations.
|
||||
long[][] data = new long[maxMag][6];
|
||||
long startTime;
|
||||
long endTime;
|
||||
|
||||
for(int i=1; i<=maxMag; i++){
|
||||
//figure out the number of iterations
|
||||
int limit = (int) Math.pow(10, i);
|
||||
//put number of iterations in table.
|
||||
data[i-1][0]=limit;
|
||||
|
||||
//array stack
|
||||
System.out.println("mag "+i+" arrayStack");
|
||||
ArrayStack arrayStack = new ArrayStack(limit);
|
||||
startTime = System.nanoTime();
|
||||
for(int j=0; j<limit; j++){
|
||||
arrayStack.push(j);
|
||||
}
|
||||
for(int j=0; j<limit; j++){
|
||||
arrayStack.pop();
|
||||
}
|
||||
endTime = System.nanoTime();
|
||||
data[i-1][1]=endTime-startTime;
|
||||
arrayStack = null;
|
||||
|
||||
//linked stack
|
||||
System.out.println("mag "+i+" linkedStack");
|
||||
LinkedStack linkedStack = new LinkedStack();
|
||||
startTime = System.nanoTime();
|
||||
for(int j=0; j<limit; j++){
|
||||
linkedStack.push(j);
|
||||
}
|
||||
for(int j=0; j<limit; j++){
|
||||
linkedStack.pop();
|
||||
}
|
||||
endTime = System.nanoTime();
|
||||
data[i-1][2]=endTime-startTime;
|
||||
linkedStack = null;
|
||||
|
||||
//array queue
|
||||
System.out.println("mag "+i+" arrayQueue");
|
||||
ArrayQueue arrayQueue = new ArrayQueue(limit);
|
||||
startTime = System.nanoTime();
|
||||
for(int j=0; j<limit; j++){
|
||||
arrayQueue.enqueue(j);
|
||||
}
|
||||
for(int j=0; j<limit; j++){
|
||||
arrayQueue.dequeue();
|
||||
}
|
||||
endTime = System.nanoTime();
|
||||
data[i-1][3]=endTime-startTime;
|
||||
arrayQueue = null;
|
||||
|
||||
//linked queue
|
||||
System.out.println("mag "+i+" linkedQueue");
|
||||
LinkedQueue linkedQueue = new LinkedQueue();
|
||||
startTime = System.nanoTime();
|
||||
for(int j=0; j<limit; j++){
|
||||
linkedQueue.enqueue(j);
|
||||
}
|
||||
for(int j=0; j<limit; j++){
|
||||
linkedQueue.dequeue();
|
||||
}
|
||||
endTime = System.nanoTime();
|
||||
data[i-1][4]=endTime-startTime;
|
||||
linkedQueue = null;
|
||||
|
||||
//array list
|
||||
System.out.println("mag "+i+" arrayList");
|
||||
ArrayList arrayList = new ArrayList();//testing the auto grow
|
||||
startTime = System.nanoTime();
|
||||
for(int j=0; j<limit; j++){
|
||||
arrayList.add(j, j);
|
||||
}
|
||||
for(int j=limit-1; j>0; j--){ //this takes AGES if i remove at index 0 with an incrementing loop due to having to shift everything.
|
||||
arrayList.remove(j);
|
||||
}
|
||||
endTime = System.nanoTime();
|
||||
data[i-1][5]=endTime-startTime;
|
||||
arrayList = null;
|
||||
}
|
||||
|
||||
//now we make an array of strings and format the numbers nicely...
|
||||
String[][] strings = new String[maxMag][6];
|
||||
for(int i=0; i<data.length; i++){
|
||||
for(int j=0; j<data[i].length; j++){
|
||||
strings[i][j]=String.format("%,d", data[i][j]);
|
||||
}
|
||||
}
|
||||
|
||||
//and print out the table.
|
||||
System.out.println(ASCIITable.render(strings, 2));
|
||||
}
|
||||
}
|
21
Lab105-VenbergGE/src/LinkedQueue.java
Normal file
21
Lab105-VenbergGE/src/LinkedQueue.java
Normal file
|
@ -0,0 +1,21 @@
|
|||
/*
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragment 6.11
|
||||
*
|
||||
* An implementation of the LinkedQueue class
|
||||
* */
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public class LinkedQueue<E> implements Queue<E>{
|
||||
private SinglyLinkedList<E> list = new SinglyLinkedList(); //an empty list
|
||||
public LinkedQueue(){} //new queue relies on initaly empty list
|
||||
public int size(){return list.size();}
|
||||
public boolean isEmpty(){return list.isEmpty();}
|
||||
public void enqueue(E element){list.addLast(element);}
|
||||
public E first(){return list.first();}
|
||||
public E dequeue(){return list.removeFirst();}
|
||||
}
|
21
Lab105-VenbergGE/src/LinkedStack.java
Normal file
21
Lab105-VenbergGE/src/LinkedStack.java
Normal file
|
@ -0,0 +1,21 @@
|
|||
/*
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragment 6.4
|
||||
*
|
||||
* An implementation of the LinkedStack class
|
||||
* */
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public class LinkedStack<E> implements Stack<E> {
|
||||
private SinglyLinkedList<E> list = new SinglyLinkedList<>(); //an empty list.
|
||||
public LinkedStack(){}; //new stack relies on initaly empty list.
|
||||
public int size(){return list.size();}
|
||||
public boolean isEmpty(){return list.isEmpty();}
|
||||
public void push(E element){list.addFirst(element);}
|
||||
public E top(){return list.first();}
|
||||
public E pop(){return list.removeFirst();}
|
||||
}
|
31
Lab105-VenbergGE/src/List.java
Normal file
31
Lab105-VenbergGE/src/List.java
Normal file
|
@ -0,0 +1,31 @@
|
|||
/*
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragment 7.1
|
||||
*
|
||||
* An implementation of the List interface
|
||||
* */
|
||||
|
||||
/**
|
||||
*a simplified version of the java.util.List interface.
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public interface List<E> {
|
||||
/** returns the number of elements in the list*/
|
||||
int size();
|
||||
|
||||
/**returns whether the list is empty*/
|
||||
boolean isEmpty();
|
||||
|
||||
/**returns but does not remove the element at index i.*/
|
||||
E get(int i) throws IndexOutOfBoundsException;
|
||||
|
||||
/**replaces the element at index i with e, and returns the replacement element.*/
|
||||
E set(int i, E e) throws IndexOutOfBoundsException;
|
||||
|
||||
/**inserts element e to be at index i, shifting all subsequent elements later*/
|
||||
void add(int i, E e) throws IndexOutOfBoundsException;
|
||||
|
||||
/**removes and returns the element at index i, shifting subsequent elements earlier*/
|
||||
E remove(int i) throws IndexOutOfBoundsException;
|
||||
}
|
28
Lab105-VenbergGE/src/Queue.java
Normal file
28
Lab105-VenbergGE/src/Queue.java
Normal file
|
@ -0,0 +1,28 @@
|
|||
/**
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragment 6.9
|
||||
*
|
||||
* An implementation of the Queue interface
|
||||
* */
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public interface Queue<E> {
|
||||
/** returns the number of elements in the queue*/
|
||||
int size();
|
||||
|
||||
/** tests whether the queue is empty*/
|
||||
boolean isEmpty();
|
||||
|
||||
/**inserts an element at the rear of the queue*/
|
||||
void enqueue(E e);
|
||||
|
||||
/**returns, but does not remove, the first element of the queue (null if empty). */
|
||||
E first();
|
||||
|
||||
/** removes and returns the first element of the queue (null if empty)*/
|
||||
E dequeue();
|
||||
}
|
78
Lab105-VenbergGE/src/SinglyLinkedList.java
Normal file
78
Lab105-VenbergGE/src/SinglyLinkedList.java
Normal file
|
@ -0,0 +1,78 @@
|
|||
/**
|
||||
*SinglyLinkedListClass
|
||||
* Code Fragments 3.14, 3.15
|
||||
* from
|
||||
* Data Structures & Algorithms, 6th edition
|
||||
* by Michael T. Goodrich, Roberto Tamassia & Michael H. Goldwasser
|
||||
* Wiley 2014
|
||||
* Transcribed by
|
||||
* @author Gabe Venberg
|
||||
*/
|
||||
public class SinglyLinkedList<E> {
|
||||
|
||||
private static class Node<E> {
|
||||
private E element; //refrence to element stored at this node
|
||||
private Node<E> next; //refrence to subsequent node of list
|
||||
|
||||
public Node(E e, Node<E> n){
|
||||
element = e;
|
||||
next = n;
|
||||
}
|
||||
|
||||
public E getElement() {return element;}
|
||||
|
||||
public Node<E> getNext() {return next;}
|
||||
|
||||
public void setNext(Node<E> n) {next = n;}
|
||||
}
|
||||
|
||||
//instance variables of SinglyLinkedList
|
||||
private Node<E> head = null;//head node of list
|
||||
private Node<E> tail = null;//last node of list
|
||||
private int size = 0;//number of nodes in list
|
||||
|
||||
public SinglyLinkedList(){}//constructs an initaly empty list
|
||||
|
||||
//access methods
|
||||
public int size() {return size;}
|
||||
|
||||
public boolean isEmpty() {return size == 0;}
|
||||
|
||||
public E first(){//returns but does not remove the first element
|
||||
if (size == 0) {return null;} //special case
|
||||
return head.getElement();
|
||||
}
|
||||
|
||||
public E last(){//returns but does not remove last elemnt
|
||||
if (size ==0) {return null;}//special case
|
||||
return tail.getElement();
|
||||
}
|
||||
|
||||
//update methods
|
||||
public void addFirst(E e){//adds element e to the front of the list
|
||||
head = new Node<>(e, head);//create and link a new node
|
||||
if (size == 0) {tail = head;}//special case, head becomes tail also
|
||||
size++;
|
||||
}
|
||||
|
||||
public void addLast(E e){//adds element to end of list
|
||||
Node<E> newest = new Node<>(e, null);//create and link a new node
|
||||
if(size == 0){//special case, previously empty list
|
||||
head = newest;
|
||||
}
|
||||
else{
|
||||
tail.setNext(newest);//new node after existing tail
|
||||
}
|
||||
tail = newest;//new node becomes tail
|
||||
size++;
|
||||
}
|
||||
|
||||
public E removeFirst(){//removes and returns the first element
|
||||
if(size == 0){return null;}//nothing to remove
|
||||
E answer = head.getElement();
|
||||
head = head.getNext();//will become null if list had only one node.
|
||||
size--;
|
||||
if(size==0){tail = null;}// special case as list is now empty
|
||||
return answer;
|
||||
}
|
||||
}
|
46
Lab105-VenbergGE/src/Stack.java
Normal file
46
Lab105-VenbergGE/src/Stack.java
Normal file
|
@ -0,0 +1,46 @@
|
|||
/**
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragment 6.1
|
||||
*
|
||||
* An implementation of the stack interface
|
||||
* */
|
||||
|
||||
/**
|
||||
* A collection of objects that are inserted and removed according to a last-in
|
||||
* first-out principle. Although similar in purpose, this interface differs from
|
||||
* java.util.stack.
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public interface Stack<E> {
|
||||
|
||||
/**
|
||||
* returns the number of elements in the stack
|
||||
* @return number of elements in the stack.
|
||||
*/
|
||||
int size();
|
||||
|
||||
/**
|
||||
* tests whether the stack is empty.
|
||||
* @return true if stack is empty, false otherwise.
|
||||
*/
|
||||
boolean isEmpty();
|
||||
|
||||
/**
|
||||
* inserts an element at the top of the stack.
|
||||
* @param e the element to be inserted.
|
||||
*/
|
||||
void push(E e);
|
||||
|
||||
/**
|
||||
* returns, but does not remove, the top element of the stack.
|
||||
* @return top element of the stack or null if empty.
|
||||
*/
|
||||
E top();
|
||||
|
||||
/**
|
||||
* removes and returns the top element from the stack.
|
||||
* @return element removed or null if empty.
|
||||
*/
|
||||
E pop();
|
||||
}
|
3
Lab106-VenbergGE/manifest.mf
Normal file
3
Lab106-VenbergGE/manifest.mf
Normal file
|
@ -0,0 +1,3 @@
|
|||
Manifest-Version: 1.0
|
||||
X-COMMENT: Main-Class will be added automatically by build
|
||||
|
93
Lab106-VenbergGE/src/Client.java
Normal file
93
Lab106-VenbergGE/src/Client.java
Normal file
|
@ -0,0 +1,93 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public class Client {
|
||||
|
||||
private static boolean isPrime(int n) {
|
||||
for (int i = 2; i < n / 2; i++) {
|
||||
if (n % i == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
LuckyNumberList luckyNumbers = new LuckyNumberList();
|
||||
|
||||
luckyNumbers.addLuckyNumber(new LuckyNumber("alice"));
|
||||
luckyNumbers.addLuckyNumber(new LuckyNumber("bob"));
|
||||
luckyNumbers.addLuckyNumber(new LuckyNumber("bill"));
|
||||
luckyNumbers.addLuckyNumber(new LuckyNumber("jill"));
|
||||
luckyNumbers.addLuckyNumber(new LuckyNumber("gabe"));
|
||||
luckyNumbers.addLuckyNumber(new LuckyNumber("erica"));
|
||||
luckyNumbers.addLuckyNumber(new LuckyNumber("albrich"));
|
||||
luckyNumbers.addLuckyNumber(new LuckyNumber("orianna"));
|
||||
luckyNumbers.addLuckyNumber(new LuckyNumber("maritt"));
|
||||
luckyNumbers.addLuckyNumber(new LuckyNumber("joe"));
|
||||
|
||||
Iterator<Position<LuckyNumber>> iterator;
|
||||
String format = "%1$10s, %2$10d %3$10s %4$10s %n";
|
||||
|
||||
iterator = luckyNumbers.positions().iterator();
|
||||
System.out.println("full iterator:");
|
||||
while (iterator.hasNext()) {
|
||||
LuckyNumber n = iterator.next().getElement();
|
||||
String even = "odd";
|
||||
String prime = "not prime";
|
||||
if (n.getLuckyNumber() % 2 == 0) {
|
||||
even = "even";
|
||||
} else if (isPrime(n.getLuckyNumber())) {
|
||||
prime = "prime";
|
||||
}
|
||||
System.out.printf(format, n.getName(), n.getLuckyNumber(), even, prime);
|
||||
}
|
||||
|
||||
System.out.println("even iterator:");
|
||||
iterator = luckyNumbers.EvenPositions().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
LuckyNumber n = iterator.next().getElement();
|
||||
String even = "odd";
|
||||
String prime = "not prime";
|
||||
if (n.getLuckyNumber() % 2 == 0) {
|
||||
even = "even";
|
||||
} else if (isPrime(n.getLuckyNumber())) {
|
||||
prime = "prime";
|
||||
}
|
||||
System.out.printf(format, n.getName(), n.getLuckyNumber(), even, prime);
|
||||
}
|
||||
|
||||
System.out.println("prime iterator");
|
||||
iterator = luckyNumbers.PrimePositions().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
LuckyNumber n = iterator.next().getElement();
|
||||
String even = "odd";
|
||||
String prime = "not prime";
|
||||
if (n.getLuckyNumber() % 2 == 0) {
|
||||
even = "even";
|
||||
} else if (isPrime(n.getLuckyNumber())) {
|
||||
prime = "prime";
|
||||
}
|
||||
System.out.printf(format, n.getName(), n.getLuckyNumber(), even, prime);
|
||||
}
|
||||
}
|
||||
}
|
10
Lab106-VenbergGE/src/Iterable.java
Normal file
10
Lab106-VenbergGE/src/Iterable.java
Normal file
|
@ -0,0 +1,10 @@
|
|||
/**
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrick, Tamassia, Goldwasser
|
||||
* Section 7.4.1
|
||||
*/
|
||||
public interface Iterable<E> {
|
||||
|
||||
Iterator<E> iterator( ); // Returns an iterator of the elements in the collection
|
||||
|
||||
}
|
20
Lab106-VenbergGE/src/Iterator.java
Normal file
20
Lab106-VenbergGE/src/Iterator.java
Normal file
|
@ -0,0 +1,20 @@
|
|||
/**
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrick, Tamassia, Goldwasser
|
||||
* Section 7.4
|
||||
*/
|
||||
public interface Iterator<E> {
|
||||
|
||||
boolean hasNext( ); // Returns true if there is at least one additional
|
||||
// element in the sequence, and false otherwise.
|
||||
|
||||
E next( ); // Returns the next element in the sequence.
|
||||
|
||||
void remove( ) throws IllegalStateException;
|
||||
// Removes from the collection the element returned by
|
||||
// the most recent call to next( ). Throws an
|
||||
// IllegalStateException if next has not yet been called,
|
||||
// or if remove was already called since the most recent
|
||||
// call to next.
|
||||
|
||||
}
|
224
Lab106-VenbergGE/src/LinkedPositionalList.java
Normal file
224
Lab106-VenbergGE/src/LinkedPositionalList.java
Normal file
|
@ -0,0 +1,224 @@
|
|||
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/*
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragments 7.9-12 and 7.14
|
||||
*
|
||||
* An implementation of the linkedpositionallist class
|
||||
*/
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public class LinkedPositionalList<E> implements PositionalList<E>{
|
||||
|
||||
//nested node class
|
||||
private static class Node<E> implements Position<E>{
|
||||
//refrence to the element stored at this node
|
||||
private E element;
|
||||
//refrence to the previous node on the list
|
||||
private Node<E> prev;
|
||||
//refrence to the next node on the list
|
||||
private Node<E> next;
|
||||
public Node (E e, Node<E> p, Node<E> n){
|
||||
element = e;
|
||||
prev = p;
|
||||
next = n;
|
||||
}
|
||||
|
||||
public E getElement() throws IllegalStateException{
|
||||
//convention for defunct node
|
||||
if(next==null){throw new IllegalStateException("position no longer valid");}
|
||||
return element;
|
||||
}
|
||||
|
||||
public Node<E> getPrev(){
|
||||
return prev;
|
||||
}
|
||||
|
||||
public Node<E> getNext(){
|
||||
return next;
|
||||
}
|
||||
|
||||
public void setElement(E e){
|
||||
element = e;
|
||||
}
|
||||
|
||||
public void setPrev(Node<E> p){
|
||||
prev=p;
|
||||
}
|
||||
|
||||
public void setNext(Node<E> n){
|
||||
next=n;
|
||||
}
|
||||
}
|
||||
//end of nested node class.
|
||||
|
||||
//nested positoniterator class
|
||||
private class PositionIterator implements Iterator<Position<E>>{
|
||||
//position of next element to report
|
||||
private Position<E> cursor = first();
|
||||
|
||||
//position of last reported element
|
||||
private Position<E> recent = null;
|
||||
|
||||
/**tests whether the iterator has a next object*/
|
||||
public boolean hasNext(){return (cursor!=null);}
|
||||
|
||||
/**returns the next position in the iterator*/
|
||||
public Position<E> next()throws NoSuchElementException{
|
||||
if(cursor==null){throw new NoSuchElementException("nothing left");}
|
||||
//element at this position might later be removed
|
||||
recent = cursor;
|
||||
cursor = after(cursor);
|
||||
return recent;
|
||||
}
|
||||
|
||||
/**removes the element removed by most recent call to next*/
|
||||
public void remove()throws IllegalStateException{
|
||||
if(recent==null){throw new IllegalStateException("nothing to remove");}
|
||||
//remove from outer list
|
||||
LinkedPositionalList.this.remove(recent);
|
||||
//do not remove again untill next is called
|
||||
recent = null;
|
||||
}
|
||||
//end of nested positionIterator class.
|
||||
|
||||
//nested positioniterable class
|
||||
private class PositionIterable implements Iterable<Position<E>>{
|
||||
public Iterator<Position<E>> iterator(){return new PositionIterator();}
|
||||
}
|
||||
//end of positioniterable class
|
||||
|
||||
//retursn an iterable representation of the lists positions*/
|
||||
public Iterable<Position<E>> positions(){
|
||||
return new PositionIterable();
|
||||
}
|
||||
|
||||
//nested elementIterator class
|
||||
/*this class adapts the iteration produced by positions to return elements*/
|
||||
private class ElementIterator implements Iterator<E>{
|
||||
Iterator<Position<E>> posIterator = new PositionIterator();
|
||||
public boolean hasNext(){return posIterator.hasNext();}
|
||||
//return element
|
||||
public E next(){return posIterator.next().getElement();}
|
||||
public void remove(){posIterator.remove();}
|
||||
}
|
||||
|
||||
public Iterator<E> iterator(){return new ElementIterator();}
|
||||
}
|
||||
|
||||
//instance variables of LinkedPositonalList
|
||||
//header sentinel
|
||||
private Node<E> header;
|
||||
//trailer sentinel
|
||||
private Node<E> trailer;
|
||||
//number of elements in list
|
||||
private int size=0;
|
||||
|
||||
/**constructs a new empty list*/
|
||||
public LinkedPositionalList(){
|
||||
header = new Node<>(null, null, null);
|
||||
trailer = new Node<>(null, header, null);
|
||||
header.setNext(trailer);
|
||||
}
|
||||
|
||||
//private utilities
|
||||
/**validates the position and returns it as a node*/
|
||||
private Node<E> validate(Position<E> p) throws IllegalArgumentException{
|
||||
if(!(p instanceof Node)) throw new IllegalArgumentException("invalid p");
|
||||
//safe cast
|
||||
Node<E> node = (Node<E>) p;
|
||||
//convention for defunct node
|
||||
if(node.getNext()==null){throw new IllegalArgumentException("p is no longer in the list");}
|
||||
return node;
|
||||
}
|
||||
|
||||
/**returns the given node as a position (or null, if it is a sentinel)*/
|
||||
private Position<E> position(Node<E> node){
|
||||
//dont expose user to sentinels
|
||||
if(node==header||node==trailer){
|
||||
return null;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
//nested position
|
||||
//public accessor methods
|
||||
/**returns the number of elements in the linked list*/
|
||||
public int size(){return size;}
|
||||
|
||||
/** tests whether the linked list is empty*/
|
||||
public boolean isEmpty(){return size==0;}
|
||||
|
||||
/**returns the first postion in the linked list (or null, if empty)*/
|
||||
public Position<E> first(){return position(header.getNext());}
|
||||
|
||||
/**returns the last postion in the linked list (or null, if empty)*/
|
||||
public Position<E> last(){return position(header.getNext());}
|
||||
|
||||
/**returns the postion immediately before position p (or null, if p is first*/
|
||||
public Position<E> before(Position<E> p) throws IllegalArgumentException{
|
||||
Node<E> node = validate(p);
|
||||
return position(node.getPrev());
|
||||
}
|
||||
|
||||
public Position<E> after(Position<E> p) throws IllegalArgumentException{
|
||||
Node<E> node = validate(p);
|
||||
return position(node.getNext());
|
||||
}
|
||||
|
||||
//private utilites
|
||||
private Position<E> addBetween(E e, Node<E> pred, Node<E> succ){
|
||||
//create and link a new node
|
||||
Node<E> newest = new Node<>(e, pred, succ);
|
||||
pred.setNext(newest);
|
||||
succ.setPrev(newest);
|
||||
size++;
|
||||
return newest;
|
||||
}
|
||||
|
||||
//public update methods
|
||||
/**inserts element e at the front of the linked list and returns its new position*/
|
||||
public Position<E> addFirst(E e){return addBetween(e, header, header.getNext());}
|
||||
|
||||
/**inserts element e at the back fo the linked list and returns its new postiton*/
|
||||
public Position<E> addLast(E e){return addBetween(e, trailer.getPrev(), trailer);}
|
||||
|
||||
/**inserts element e immediately before position p, and returns its new position*/
|
||||
public Position<E> addBefore(Position<E> p, E e) throws IllegalArgumentException{
|
||||
Node<E> node = validate(p);
|
||||
return addBetween(e, node.getPrev(), node);
|
||||
}
|
||||
|
||||
/**inserts element e immediately after position p, and returns its new position*/
|
||||
public Position<E> addAfter(Position<E> p, E e){
|
||||
Node<E> node = validate(p);
|
||||
return addBetween(e, node, node.getNext());
|
||||
}
|
||||
|
||||
/**replaces the element stored at position p and returns the old element*/
|
||||
public E set(Position<E> p, E e) throws IllegalArgumentException{
|
||||
Node<E> node = validate(p);
|
||||
E answer = node.getElement();
|
||||
node.setElement(e);
|
||||
return answer;
|
||||
}
|
||||
|
||||
/**removes the element stored at Position p and returns it (invalidating p)*/
|
||||
public E remove(Position<E> p) throws IllegalArgumentException{
|
||||
Node<E> node = validate(p);
|
||||
Node<E> predecessor = node.getPrev();
|
||||
Node<E> succsessor = node.getNext();
|
||||
predecessor.setNext(succsessor);
|
||||
succsessor.setPrev(predecessor);
|
||||
size--;
|
||||
E answer = node.getElement();
|
||||
node.setElement(null);
|
||||
node.setNext(null);
|
||||
node.setPrev(null);
|
||||
return answer;
|
||||
}
|
||||
}
|
48
Lab106-VenbergGE/src/LuckyNumber.java
Normal file
48
Lab106-VenbergGE/src/LuckyNumber.java
Normal file
|
@ -0,0 +1,48 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
import java.util.Random;
|
||||
public class LuckyNumber {
|
||||
private String name;
|
||||
private int luckyNumber;
|
||||
|
||||
Random rand = new Random();
|
||||
|
||||
public LuckyNumber(String name){
|
||||
this.name = name;
|
||||
luckyNumber = rand.nextInt(10);
|
||||
}
|
||||
|
||||
public String getName(){return name;}
|
||||
|
||||
public int getLuckyNumber(){return luckyNumber;}
|
||||
|
||||
public boolean equals(Object o){
|
||||
if (!(o instanceof LuckyNumber)){return false;}
|
||||
LuckyNumber l = (LuckyNumber) o;
|
||||
return name.equals(l.name)
|
||||
&& luckyNumber == l.luckyNumber;
|
||||
}
|
||||
|
||||
public String toString(){
|
||||
return getClass().getName() + ':'+name+';'+luckyNumber;
|
||||
}
|
||||
}
|
143
Lab106-VenbergGE/src/LuckyNumberList.java
Normal file
143
Lab106-VenbergGE/src/LuckyNumberList.java
Normal file
|
@ -0,0 +1,143 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public class LuckyNumberList {
|
||||
private LinkedPositionalList<LuckyNumber> luckyNumbers;
|
||||
|
||||
public LuckyNumberList(){
|
||||
luckyNumbers = new LinkedPositionalList<LuckyNumber>();
|
||||
}
|
||||
|
||||
public void addLuckyNumber(LuckyNumber l){
|
||||
luckyNumbers.addLast(l);
|
||||
}
|
||||
|
||||
private class positionIterator implements Iterator<Position<LuckyNumber>>{
|
||||
private Position<LuckyNumber> cursor = luckyNumbers.first();
|
||||
private Position<LuckyNumber> recent = null;
|
||||
|
||||
public boolean hasNext(){return(cursor!=null);}
|
||||
|
||||
public Position<LuckyNumber> next() throws NoSuchElementException {
|
||||
if(cursor==null){throw new NoSuchElementException("nothing left");}
|
||||
recent = cursor;
|
||||
cursor = luckyNumbers.after(cursor);
|
||||
return recent;
|
||||
}
|
||||
public void remove() throws IllegalStateException{
|
||||
if(recent==null){throw new IllegalStateException("nothing to remove");}
|
||||
luckyNumbers.remove(recent);
|
||||
recent=null;
|
||||
}
|
||||
}
|
||||
|
||||
private class positionIterable implements Iterable<Position<LuckyNumber>>{
|
||||
public Iterator<Position<LuckyNumber>> iterator(){return new positionIterator();}
|
||||
}
|
||||
|
||||
public Iterable<Position<LuckyNumber>> positions(){
|
||||
return new positionIterable();
|
||||
}
|
||||
|
||||
private class EvenPositionIterator implements Iterator<Position<LuckyNumber>>{
|
||||
private Position<LuckyNumber> cursor = luckyNumbers.first();
|
||||
private Position<LuckyNumber> recent = null;
|
||||
|
||||
public boolean hasNext(){return(cursor!=null);}
|
||||
|
||||
public Position<LuckyNumber> next() throws NoSuchElementException {
|
||||
if(cursor==null){throw new NoSuchElementException("nothing left");}
|
||||
if(recent==null){
|
||||
while((cursor != null) && !(cursor.getElement().getLuckyNumber()%2==0)){
|
||||
cursor = luckyNumbers.after(cursor);
|
||||
}
|
||||
}
|
||||
recent = cursor;
|
||||
cursor = luckyNumbers.after(cursor);
|
||||
//advance cursor to next even number
|
||||
while((cursor != null) && !(cursor.getElement().getLuckyNumber()%2==0)){
|
||||
cursor = luckyNumbers.after(cursor);
|
||||
}
|
||||
return recent;
|
||||
}
|
||||
public void remove() throws IllegalStateException{
|
||||
if(recent==null){throw new IllegalStateException("nothing to remove");}
|
||||
luckyNumbers.remove(recent);
|
||||
recent=null;
|
||||
}
|
||||
}
|
||||
|
||||
private class EvenPositionIterable implements Iterable<Position<LuckyNumber>>{
|
||||
public Iterator<Position<LuckyNumber>> iterator(){return new EvenPositionIterator();}
|
||||
}
|
||||
|
||||
public Iterable<Position<LuckyNumber>> EvenPositions(){
|
||||
return new EvenPositionIterable();
|
||||
}
|
||||
|
||||
//utility class
|
||||
private boolean isPrime(int n){
|
||||
for(int i=2; i<n/2;i++){
|
||||
if(n%i==0){return false;}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private class PrimePositionIterator implements Iterator<Position<LuckyNumber>>{
|
||||
private Position<LuckyNumber> cursor = luckyNumbers.first();
|
||||
private Position<LuckyNumber> recent = null;
|
||||
|
||||
public boolean hasNext(){return(cursor!=null);}
|
||||
|
||||
public Position<LuckyNumber> next() throws NoSuchElementException {
|
||||
if(cursor==null){throw new NoSuchElementException("nothing left");}
|
||||
if(recent==null){
|
||||
while(cursor != null && !isPrime(cursor.getElement().getLuckyNumber())){
|
||||
cursor = luckyNumbers.after(cursor);
|
||||
}
|
||||
}
|
||||
recent = cursor;
|
||||
cursor = luckyNumbers.after(cursor);
|
||||
//advance cursor to next even number
|
||||
while(cursor != null && !isPrime(cursor.getElement().getLuckyNumber())){
|
||||
cursor = luckyNumbers.after(cursor);
|
||||
}
|
||||
return recent;
|
||||
}
|
||||
public void remove() throws IllegalStateException{
|
||||
if(recent==null){throw new IllegalStateException("nothing to remove");}
|
||||
luckyNumbers.remove(recent);
|
||||
recent=null;
|
||||
}
|
||||
}
|
||||
|
||||
private class PrimePositionIterable implements Iterable<Position<LuckyNumber>>{
|
||||
public Iterator<Position<LuckyNumber>> iterator(){return new PrimePositionIterator();}
|
||||
}
|
||||
|
||||
public Iterable<Position<LuckyNumber>> PrimePositions(){
|
||||
return new PrimePositionIterable();
|
||||
}
|
||||
|
||||
|
||||
}
|
21
Lab106-VenbergGE/src/Position.java
Normal file
21
Lab106-VenbergGE/src/Position.java
Normal file
|
@ -0,0 +1,21 @@
|
|||
/*
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragment 7.7
|
||||
*
|
||||
* An implementation of the position interface
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public interface Position<E> {
|
||||
/**
|
||||
* Returns the element stored at this position
|
||||
*
|
||||
* @return the stored element
|
||||
* @throws IllegalStateException if position no longer valid.
|
||||
*/
|
||||
E getElement() throws IllegalStateException;
|
||||
}
|
50
Lab106-VenbergGE/src/PositionalList.java
Normal file
50
Lab106-VenbergGE/src/PositionalList.java
Normal file
|
@ -0,0 +1,50 @@
|
|||
/*
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragment 7.8
|
||||
*
|
||||
* An implementation of the positionalList interface
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public interface PositionalList<E> {
|
||||
|
||||
/** returns the number of elements in the list*/
|
||||
int size();
|
||||
|
||||
/**tests whether the list is empty*/
|
||||
boolean isEmpty();
|
||||
|
||||
/**returns the first position in the list (or null if empty)*/
|
||||
Position<E> first();
|
||||
|
||||
/**returns the last position in the list (or null if empty)*/
|
||||
Position<E> last();
|
||||
|
||||
/**returns the position immediately before position p (or null, if p is first)*/
|
||||
Position<E> before(Position<E> p) throws IllegalArgumentException;
|
||||
|
||||
/**returns the position immediately after position p (or null, if p is last)*/
|
||||
Position<E> after(Position<E> p) throws IllegalArgumentException;
|
||||
|
||||
/**inserts element e at the front of the list and returns its new position*/
|
||||
Position<E> addFirst(E e);
|
||||
|
||||
/**inserts element e at the back of the list and returns its new position*/
|
||||
Position<E> addLast(E e);
|
||||
|
||||
/**inserts element e immediately before position p and returns its new position*/
|
||||
Position<E> addBefore(Position<E> p, E e) throws IllegalArgumentException;
|
||||
|
||||
/**inserts element e immediately after Position p and returns its new position*/
|
||||
Position<E> addAfter(Position<E> p, E e) throws IllegalArgumentException;
|
||||
|
||||
/**replaces the element stored at position p and returns the replaced element*/
|
||||
E set(Position<E> p, E e) throws IllegalArgumentException;
|
||||
|
||||
/**removes the element stored at position p and returns it (invalidating p)*/
|
||||
E remove(Position<E> p) throws IllegalArgumentException;
|
||||
}
|
3
Lab107-VenbergGE/manifest.mf
Normal file
3
Lab107-VenbergGE/manifest.mf
Normal file
|
@ -0,0 +1,3 @@
|
|||
Manifest-Version: 1.0
|
||||
X-COMMENT: Main-Class will be added automatically by build
|
||||
|
76
Lab107-VenbergGE/src/AbstractBinaryTree.java
Normal file
76
Lab107-VenbergGE/src/AbstractBinaryTree.java
Normal file
|
@ -0,0 +1,76 @@
|
|||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
/*
|
||||
* * Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragments 8.7, 8.26, 8.22
|
||||
*\
|
||||
|
||||
/**
|
||||
* an abstract base class providing some functionality of the binarytree interface
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public abstract class AbstractBinaryTree<E> extends AbstractTree<E> implements BinaryTree<E> {
|
||||
public Position<E> sibling(Position<E> p){
|
||||
Position<E> parent = parent(p);
|
||||
//p is root.
|
||||
if (parent == null){return null;}
|
||||
//p is left child, right child might be null.
|
||||
if (p==left(parent)){return right(parent);}
|
||||
//p is right child, left child might be null.
|
||||
else {return left(parent);}
|
||||
}
|
||||
|
||||
/**returns the number of children of Position p*/
|
||||
public int numChildren(Position<E> p){
|
||||
int count=0;
|
||||
if (left(p)!=null){count++;}
|
||||
if(right(p)!=null){count++;}
|
||||
return count;
|
||||
}
|
||||
|
||||
/**returns an iterable collection of Positions representing p's children.*/
|
||||
public Iterable<Position<E>> children(Position<E> p){
|
||||
//max capacity of 2
|
||||
List <Position<E>> snapshot=new ArrayList<>(2);
|
||||
//needed to modify this, as the arraylist we made in class needed an index
|
||||
if(left(p)!=null){snapshot.add(left(p));}
|
||||
if(right(p)!=null){snapshot.add(right(p));}
|
||||
// and our arraylist
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/**adds positions of the subtree rooted at Position p to the given snapshot*/
|
||||
private void inorderSubtree(Position<E> p, List<Position<E>> snapshot){
|
||||
if(left(p)!=null){inorderSubtree(left(p), snapshot);}
|
||||
snapshot.add(p);
|
||||
if(right(p)!=null){inorderSubtree(right(p), snapshot);}
|
||||
}
|
||||
|
||||
/**returns an iterable collection of the positions of the tree, reported in inorder.*/
|
||||
public Iterable<Position<E>> inorder(){
|
||||
List<Position<E>> snapshot=new ArrayList<>();
|
||||
//fill snapshot recursively
|
||||
if(!isEmpty()){inorderSubtree(root(), snapshot);}
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/**Overrides positions to make inorder the default order for binary trees*/
|
||||
public Iterable<Position<E>> positions(){
|
||||
return inorder();
|
||||
}
|
||||
|
||||
//nested ElementIterator class
|
||||
/**this class adapts the iteration produced by positions() to returns elements*/
|
||||
private class ElementIterator implements Iterator<E>{
|
||||
Iterator<Position<E>> posIterator=positions().iterator();
|
||||
public boolean hasNext(){return posIterator.hasNext();}
|
||||
//return element
|
||||
public E next(){return posIterator.next().getElement();}
|
||||
public void remove(){posIterator.remove();}
|
||||
}//end of nested ElementIterator class
|
||||
|
||||
/**returns an iterator if the elements stored in the tree*/
|
||||
public Iterator<E> iterator(){return new ElementIterator();}
|
||||
}
|
104
Lab107-VenbergGE/src/AbstractTree.java
Normal file
104
Lab107-VenbergGE/src/AbstractTree.java
Normal file
|
@ -0,0 +1,104 @@
|
|||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/*
|
||||
* * Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragments 8.2-8.5, 8.19-21
|
||||
*\
|
||||
/*
|
||||
* an abstract base class providing some functionality of the tree interface.
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public abstract class AbstractTree<E> implements Tree<E> {
|
||||
public boolean isInternal(Position<E> p) {return numChildren(p)>0;}
|
||||
public boolean isExternal(Position<E> p){return numChildren(p)==0;}
|
||||
public boolean isRoot(Position<E> p){return p == root();}
|
||||
public boolean isEmpty(){return size()==0;}
|
||||
|
||||
/**returns the number of levels sperating position p from the root.*/
|
||||
public int depth(Position<E> p){
|
||||
if (isRoot(p)){return 0;}
|
||||
else{return 1+depth(parent(p));}
|
||||
}
|
||||
|
||||
/**returns the hight of the tree.*/
|
||||
private int hightBad(){ //works, but quadratic worst case time.
|
||||
int h=0;
|
||||
for(Position<E> p : positions()){
|
||||
//only consider leaf positions.
|
||||
if(isExternal(p)){h=Math.max(h, depth(p));}
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
/**returns the hight of the subtree rooted at position p.*/
|
||||
public int hight(Position<E> p){
|
||||
//base case if p is external
|
||||
int h=0;
|
||||
for (Position<E> c : children(p)){
|
||||
h=Math.max(h,1+hight(c));
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
//iterators
|
||||
/**adds positions of the subtree rooted at position p to the given snapshot (for use in traversal)*/
|
||||
private void preorderSubtree(Position<E> p, List<Position<E>> snapshot){
|
||||
//for preorder, add position p before exploring subtrees.
|
||||
snapshot.add(p);
|
||||
for(Position<E> c:children(p)){
|
||||
preorderSubtree(c, snapshot);
|
||||
}
|
||||
}
|
||||
|
||||
/**returns an iterable collection of positions in the tree, reported in preorder*/
|
||||
public Iterable<Position<E>> preorder(){
|
||||
List<Position<E>> snapshot=new ArrayList<>();
|
||||
//fill the snapshot recursively
|
||||
if(!isEmpty()){
|
||||
preorderSubtree(root(), snapshot);
|
||||
}
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/**adds positions of the subtree rooted at position p to the given snapshot (for use in traversal)*/
|
||||
private void postorderSubtree(Position<E> p, List<Position<E>> snapshot){
|
||||
//for postorder, add position p before exploring subtrees.
|
||||
for(Position<E> c:children(p)){
|
||||
postorderSubtree(c, snapshot);
|
||||
}
|
||||
snapshot.add(p);
|
||||
}
|
||||
|
||||
/**returns an iterable collection of positions in the tree, reported in postorder*/
|
||||
public Iterable<Position<E>> postorder(){
|
||||
List<Position<E>> snapshot=new ArrayList<>();
|
||||
//fill the snapshot recursively
|
||||
if(!isEmpty()){
|
||||
postorderSubtree(root(), snapshot);
|
||||
}
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/**returns an iterable collection of positions in the tree in breadth first traversal*/
|
||||
public Iterable<Position<E>> breadthFirst(){
|
||||
List<Position<E>> snapshot=new ArrayList<>();
|
||||
if(!isEmpty()){
|
||||
Queue<Position<E>> fringe=new LinkedQueue<>();
|
||||
fringe.enqueue(root());
|
||||
while(!fringe.isEmpty()){
|
||||
Position<E> p=fringe.dequeue();
|
||||
snapshot.add(p);
|
||||
for(Position<E> c:children(p)){
|
||||
fringe.enqueue(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/**default iterator*/
|
||||
public Iterable<Position<E>> positions(){return preorder();}
|
||||
}
|
18
Lab107-VenbergGE/src/BinaryTree.java
Normal file
18
Lab107-VenbergGE/src/BinaryTree.java
Normal file
|
@ -0,0 +1,18 @@
|
|||
/*
|
||||
* * Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragments 8.6
|
||||
*\
|
||||
|
||||
\**
|
||||
*an interface for a binary tree, in which each node has at most two children.
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public interface BinaryTree<E> extends Tree<E> {
|
||||
/**returns the position of p's left child (or null if no child exists).*/
|
||||
Position<E> left(Position<E> p) throws IllegalArgumentException;
|
||||
/**returns the position of p's right child (or null if no child exists)*/
|
||||
Position<E> right(Position<E> p) throws IllegalArgumentException;
|
||||
/**returns the position of p's sibling (or null of no sibling exists).*/
|
||||
Position <E> sibling(Position<E> p) throws IllegalArgumentException;
|
||||
}
|
82
Lab107-VenbergGE/src/Client.java
Normal file
82
Lab107-VenbergGE/src/Client.java
Normal file
|
@ -0,0 +1,82 @@
|
|||
/*
|
||||
* Copyright (C) 2021 Gabriel Venberg
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public class Client {
|
||||
public static void main(String[] args){
|
||||
LinkedBinaryTree<String> expression = new LinkedBinaryTree<String>();
|
||||
|
||||
expression.addRoot("+");
|
||||
LinkedBinaryTree tmp = new LinkedBinaryTree();
|
||||
LinkedBinaryTree tmp2 = new LinkedBinaryTree();
|
||||
tmp.addRoot("+");
|
||||
tmp.addLeft(tmp.root(), "2");
|
||||
tmp.addRight(tmp.root(), "9");
|
||||
|
||||
tmp2.addRoot("-");
|
||||
tmp2.addLeft(tmp2.root(), "7");
|
||||
tmp2.addRight(tmp2.root(), "*");
|
||||
tmp2.addLeft(tmp2.right(tmp2.root()), "3");
|
||||
tmp2.addRight(tmp2.right(tmp2.root()), "8");
|
||||
|
||||
expression.attach(expression.root(), tmp, tmp2);
|
||||
|
||||
System.out.println("literal expression is: ( 2 + 9 ) + ( 7 - ( 3 * 8 ) )");
|
||||
|
||||
System.out.println("hight is: "+expression.hight(expression.root()));
|
||||
|
||||
System.out.println("preorder is:");
|
||||
for(Position s:expression.preorder()){
|
||||
System.out.print(s.getElement());
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
System.out.println("inorder is:");
|
||||
for(Position s:expression.inorder()){
|
||||
System.out.print(s.getElement());
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
System.out.println("postorder is:");
|
||||
for(Position s:expression.postorder()){
|
||||
System.out.print(s.getElement());
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
System.out.println("breadth first is:");
|
||||
for(Position s:expression.breadthFirst()){
|
||||
System.out.print(s.getElement());
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
System.out.println("parenthasized representation:");
|
||||
eulerTourPrint(expression, expression.root());
|
||||
|
||||
}
|
||||
|
||||
//utility class
|
||||
private static void eulerTourPrint(AbstractBinaryTree t, Position p){
|
||||
if(t.isInternal(p)){System.out.print('(');}
|
||||
if(t.left(p)!=null){eulerTourPrint(t, t.left(p));}
|
||||
System.out.print(p.getElement());
|
||||
if(t.right(p)!=null){eulerTourPrint(t, t.right(p));}
|
||||
if(t.isInternal(p)){System.out.print(')');}
|
||||
}
|
||||
}
|
189
Lab107-VenbergGE/src/LinkedBinaryTree.java
Normal file
189
Lab107-VenbergGE/src/LinkedBinaryTree.java
Normal file
|
@ -0,0 +1,189 @@
|
|||
/*
|
||||
* * Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragments 8.9-11
|
||||
*\
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public class LinkedBinaryTree<E> extends AbstractBinaryTree<E> {
|
||||
|
||||
//nested node class
|
||||
protected static class Node<E> implements Position<E>{
|
||||
//an element stored at this node
|
||||
private E element;
|
||||
//a reference the the parent node
|
||||
private Node<E> parent;
|
||||
//a refrence to the left node
|
||||
private Node<E> left;
|
||||
//a reference the right node
|
||||
private Node<E> right;
|
||||
|
||||
/**constructs a done with the given element and neighbors*/
|
||||
public Node(E e, Node<E> above, Node<E> leftChild, Node<E> rightChild){
|
||||
element=e;
|
||||
parent=above;
|
||||
left=leftChild;
|
||||
right=rightChild;
|
||||
}
|
||||
|
||||
//why do we set the variables to private and make these methods for a protected class? doesnt that add uneeded overhead for no benifits of encapsulation?
|
||||
//acessor methods
|
||||
public E getElement(){return element;}
|
||||
public Node<E> getParent(){return parent;}
|
||||
public Node<E> getLeft(){return left;}
|
||||
public Node<E> getRight(){return right;}
|
||||
|
||||
//update methods
|
||||
public void setElement(E e){element=e;}
|
||||
public void setParent(Node<E> parentNode){parent=parentNode;}
|
||||
public void setLeft(Node<E> leftChild){left=leftChild;}
|
||||
public void setRight(Node<E> rightChild){right=rightChild;}
|
||||
}//end of node class.
|
||||
|
||||
//why create this class? its the exact same as just using the node constructor, even the same signature!
|
||||
/**factory function to create new node storing element e*/
|
||||
protected Node<E> createNode(E e, Node<E> parent, Node<E> left, Node<E> right){
|
||||
return new Node<E>(e, parent, left, right);
|
||||
}
|
||||
|
||||
//LinkedBinaryTree instance variables
|
||||
//root of the tree
|
||||
protected Node<E> root=null;
|
||||
//number of nodes in the tree
|
||||
private int size=0;
|
||||
|
||||
//constructor
|
||||
//creats an empty binary tree
|
||||
public LinkedBinaryTree(){}
|
||||
|
||||
//nonpublic utility
|
||||
/**validates the position and returns it as a node*/
|
||||
protected Node<E> validate(Position<E> p) throws IllegalArgumentException{
|
||||
if(!(p instanceof Node)){
|
||||
throw new IllegalArgumentException("not a valid position type");
|
||||
}
|
||||
//safe cast
|
||||
Node<E> node=(Node<E>)p;
|
||||
//our convention for a defunct node. Wont this make the GC not clean it up? why not just set the parent to null and let the GC clean it up?
|
||||
if(node.getParent()==node){
|
||||
throw new IllegalArgumentException("p is no longer in the tree");
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
//acessor methods still left to implement
|
||||
/**returns the number of nodes in the tree*/
|
||||
public int size(){return size;}
|
||||
|
||||
/**returns the root position of the tree (or null if tree is empty)*/
|
||||
public Position<E> root(){return root;}
|
||||
|
||||
/**returns the position of p's parent or null if p is root*/
|
||||
public Position<E> parent(Position<E> p) throws IllegalArgumentException {
|
||||
Node<E> node=validate(p);
|
||||
return node.getParent();
|
||||
}
|
||||
|
||||
/**returns the position of p's left child (or null if no child exists)*/
|
||||
public Position<E> left(Position<E> p) throws IllegalArgumentException {
|
||||
Node<E> node = validate(p);
|
||||
return node.getLeft();
|
||||
}
|
||||
|
||||
/**returns the position of p's right child (or null if no child exists)*/
|
||||
public Position<E> right(Position<E> p) throws IllegalArgumentException {
|
||||
Node<E> node=validate(p);
|
||||
return node.getRight();
|
||||
}
|
||||
|
||||
//update methods supported
|
||||
/**places element e at the root of an empty tree and returns its new Position */
|
||||
public Position<E> addRoot(E e) throws IllegalStateException {
|
||||
if (!isEmpty()){throw new IllegalStateException("tree is not empty");}
|
||||
root=createNode(e, null, null, null);
|
||||
size=1;
|
||||
return root;
|
||||
}
|
||||
|
||||
/**creates a new left child of Position P storing element e, returns its position*/
|
||||
public Position<E> addLeft(Position<E> p, E e) throws IllegalArgumentException{
|
||||
Node<E> parent=validate(p);
|
||||
if(parent.getLeft()!=null){
|
||||
throw new IllegalArgumentException("p already has a left child");
|
||||
}
|
||||
Node<E> child=createNode(e, parent, null, null);
|
||||
parent.setLeft(child);
|
||||
size++;
|
||||
return child;
|
||||
}
|
||||
|
||||
public Position<E> addRight(Position<E> p, E e)throws IllegalArgumentException{
|
||||
Node<E> parent=validate(p);
|
||||
if(parent.getRight()!=null){
|
||||
throw new IllegalArgumentException("p already has a right child");
|
||||
}
|
||||
Node<E> child=createNode(e, parent, null, null);
|
||||
parent.setRight(child);
|
||||
size++;
|
||||
return child;
|
||||
}
|
||||
|
||||
/**replaces the element at position p with e and returns the replaced element*/
|
||||
public E set(Position<E> p, E e) throws IllegalArgumentException{
|
||||
Node<E> node=validate(p);
|
||||
E temp=node.getElement();
|
||||
node.setElement(e);
|
||||
return temp;
|
||||
}
|
||||
|
||||
/**attaches trees t1 and t2 as left and right subtrees of external p.*/
|
||||
public void attach(Position<E> p, LinkedBinaryTree<E> t1, LinkedBinaryTree<E> t2)throws IllegalArgumentException{
|
||||
Node<E> node=validate(p);
|
||||
if(isInternal(p)) throw new IllegalArgumentException("P must be a leaf");
|
||||
size+=t1.size()+t2.size();
|
||||
//set t1 as left node
|
||||
if(!t1.isEmpty()){
|
||||
t1.root.setParent(node);
|
||||
node.setLeft(t1.root);
|
||||
t1.root=null;
|
||||
t1.size=0;
|
||||
}
|
||||
|
||||
//set t2 as right node
|
||||
if(!t2.isEmpty()){
|
||||
t2.root.setParent(node);
|
||||
node.setRight(t2.root);
|
||||
t2.root=null;
|
||||
t2.size=0;
|
||||
}
|
||||
}
|
||||
/**removes the node at Position p and replaces it with its child. only works if p has 1 or 0 children*/
|
||||
public E remove(Position<E> p)throws IllegalArgumentException{
|
||||
Node<E> node=validate(p);
|
||||
if(numChildren(p)==2){throw new IllegalArgumentException("p has two children");}
|
||||
Node<E> child=(node.getLeft()!=null?node.getLeft():node.getRight());
|
||||
//childs grandparent becomes its parent
|
||||
if(child!=null){child.setParent(node.getParent());}
|
||||
|
||||
//child becomes root;
|
||||
if(node==root){root=child;}
|
||||
//child is not root, set child as child of parent
|
||||
else{
|
||||
Node<E> parent = node.getParent();
|
||||
if(node==parent.getLeft()){parent.setLeft(child);}
|
||||
else{parent.setRight(child);}
|
||||
}
|
||||
size--;
|
||||
E temp=node.getElement();
|
||||
//help java GC. sometimes I think it would be easier to do manual GC than have to baby along an auto GC.
|
||||
node.setElement(null);
|
||||
node.setLeft(null);
|
||||
node.setRight(null);
|
||||
//for some reason we set this to parent itself, instead of setting to null and sending to GC.
|
||||
node.setParent(node);
|
||||
return temp;
|
||||
}
|
||||
}
|
21
Lab107-VenbergGE/src/LinkedQueue.java
Normal file
21
Lab107-VenbergGE/src/LinkedQueue.java
Normal file
|
@ -0,0 +1,21 @@
|
|||
/*
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragment 6.11
|
||||
*
|
||||
* An implementation of the LinkedQueue class
|
||||
* */
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public class LinkedQueue<E> implements Queue<E>{
|
||||
private SinglyLinkedList<E> list = new SinglyLinkedList(); //an empty list
|
||||
public LinkedQueue(){} //new queue relies on initaly empty list
|
||||
public int size(){return list.size();}
|
||||
public boolean isEmpty(){return list.isEmpty();}
|
||||
public void enqueue(E element){list.addLast(element);}
|
||||
public E first(){return list.first();}
|
||||
public E dequeue(){return list.removeFirst();}
|
||||
}
|
21
Lab107-VenbergGE/src/Position.java
Normal file
21
Lab107-VenbergGE/src/Position.java
Normal file
|
@ -0,0 +1,21 @@
|
|||
/*
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragment 7.7
|
||||
*
|
||||
* An implementation of the position interface
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public interface Position<E> {
|
||||
/**
|
||||
* Returns the element stored at this position
|
||||
*
|
||||
* @return the stored element
|
||||
* @throws IllegalStateException if position no longer valid.
|
||||
*/
|
||||
E getElement() throws IllegalStateException;
|
||||
}
|
50
Lab107-VenbergGE/src/PositionalList.java
Normal file
50
Lab107-VenbergGE/src/PositionalList.java
Normal file
|
@ -0,0 +1,50 @@
|
|||
/*
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragment 7.8
|
||||
*
|
||||
* An implementation of the positionalList interface
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public interface PositionalList<E> {
|
||||
|
||||
/** returns the number of elements in the list*/
|
||||
int size();
|
||||
|
||||
/**tests whether the list is empty*/
|
||||
boolean isEmpty();
|
||||
|
||||
/**returns the first position in the list (or null if empty)*/
|
||||
Position<E> first();
|
||||
|
||||
/**returns the last position in the list (or null if empty)*/
|
||||
Position<E> last();
|
||||
|
||||
/**returns the position immediately before position p (or null, if p is first)*/
|
||||
Position<E> before(Position<E> p) throws IllegalArgumentException;
|
||||
|
||||
/**returns the position immediately after position p (or null, if p is last)*/
|
||||
Position<E> after(Position<E> p) throws IllegalArgumentException;
|
||||
|
||||
/**inserts element e at the front of the list and returns its new position*/
|
||||
Position<E> addFirst(E e);
|
||||
|
||||
/**inserts element e at the back of the list and returns its new position*/
|
||||
Position<E> addLast(E e);
|
||||
|
||||
/**inserts element e immediately before position p and returns its new position*/
|
||||
Position<E> addBefore(Position<E> p, E e) throws IllegalArgumentException;
|
||||
|
||||
/**inserts element e immediately after Position p and returns its new position*/
|
||||
Position<E> addAfter(Position<E> p, E e) throws IllegalArgumentException;
|
||||
|
||||
/**replaces the element stored at position p and returns the replaced element*/
|
||||
E set(Position<E> p, E e) throws IllegalArgumentException;
|
||||
|
||||
/**removes the element stored at position p and returns it (invalidating p)*/
|
||||
E remove(Position<E> p) throws IllegalArgumentException;
|
||||
}
|
28
Lab107-VenbergGE/src/Queue.java
Normal file
28
Lab107-VenbergGE/src/Queue.java
Normal file
|
@ -0,0 +1,28 @@
|
|||
/**
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragment 6.9
|
||||
*
|
||||
* An implementation of the Queue interface
|
||||
* */
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public interface Queue<E> {
|
||||
/** returns the number of elements in the queue*/
|
||||
int size();
|
||||
|
||||
/** tests whether the queue is empty*/
|
||||
boolean isEmpty();
|
||||
|
||||
/**inserts an element at the rear of the queue*/
|
||||
void enqueue(E e);
|
||||
|
||||
/**returns, but does not remove, the first element of the queue (null if empty). */
|
||||
E first();
|
||||
|
||||
/** removes and returns the first element of the queue (null if empty)*/
|
||||
E dequeue();
|
||||
}
|
78
Lab107-VenbergGE/src/SinglyLinkedList.java
Normal file
78
Lab107-VenbergGE/src/SinglyLinkedList.java
Normal file
|
@ -0,0 +1,78 @@
|
|||
/**
|
||||
*SinglyLinkedListClass
|
||||
* Code Fragments 3.14, 3.15
|
||||
* from
|
||||
* Data Structures & Algorithms, 6th edition
|
||||
* by Michael T. Goodrich, Roberto Tamassia & Michael H. Goldwasser
|
||||
* Wiley 2014
|
||||
* Transcribed by
|
||||
* @author Gabe Venberg
|
||||
*/
|
||||
public class SinglyLinkedList<E> {
|
||||
|
||||
private static class Node<E> {
|
||||
private E element; //refrence to element stored at this node
|
||||
private Node<E> next; //refrence to subsequent node of list
|
||||
|
||||
public Node(E e, Node<E> n){
|
||||
element = e;
|
||||
next = n;
|
||||
}
|
||||
|
||||
public E getElement() {return element;}
|
||||
|
||||
public Node<E> getNext() {return next;}
|
||||
|
||||
public void setNext(Node<E> n) {next = n;}
|
||||
}
|
||||
|
||||
//instance variables of SinglyLinkedList
|
||||
private Node<E> head = null;//head node of list
|
||||
private Node<E> tail = null;//last node of list
|
||||
private int size = 0;//number of nodes in list
|
||||
|
||||
public SinglyLinkedList(){}//constructs an initaly empty list
|
||||
|
||||
//access methods
|
||||
public int size() {return size;}
|
||||
|
||||
public boolean isEmpty() {return size == 0;}
|
||||
|
||||
public E first(){//returns but does not remove the first element
|
||||
if (size == 0) {return null;} //special case
|
||||
return head.getElement();
|
||||
}
|
||||
|
||||
public E last(){//returns but does not remove last elemnt
|
||||
if (size ==0) {return null;}//special case
|
||||
return tail.getElement();
|
||||
}
|
||||
|
||||
//update methods
|
||||
public void addFirst(E e){//adds element e to the front of the list
|
||||
head = new Node<>(e, head);//create and link a new node
|
||||
if (size == 0) {tail = head;}//special case, head becomes tail also
|
||||
size++;
|
||||
}
|
||||
|
||||
public void addLast(E e){//adds element to end of list
|
||||
Node<E> newest = new Node<>(e, null);//create and link a new node
|
||||
if(size == 0){//special case, previously empty list
|
||||
head = newest;
|
||||
}
|
||||
else{
|
||||
tail.setNext(newest);//new node after existing tail
|
||||
}
|
||||
tail = newest;//new node becomes tail
|
||||
size++;
|
||||
}
|
||||
|
||||
public E removeFirst(){//removes and returns the first element
|
||||
if(size == 0){return null;}//nothing to remove
|
||||
E answer = head.getElement();
|
||||
head = head.getNext();//will become null if list had only one node.
|
||||
size--;
|
||||
if(size==0){tail = null;}// special case as list is now empty
|
||||
return answer;
|
||||
}
|
||||
}
|
29
Lab107-VenbergGE/src/Tree.java
Normal file
29
Lab107-VenbergGE/src/Tree.java
Normal file
|
@ -0,0 +1,29 @@
|
|||
|
||||
import java.util.Iterator;
|
||||
|
||||
/*
|
||||
* Data Structures & Algorithms 6th Edition
|
||||
* Goodrich, Tamassia, Goldwasser
|
||||
* Code Fragment 8.1
|
||||
*
|
||||
* An implementation of the tree interface
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* An interface for a tree where nodes can have an arbitrary number of children.
|
||||
* @author Gabriel Venberg
|
||||
*/
|
||||
public interface Tree<E> extends Iterable<E>{
|
||||
Position <E> root();
|
||||
Position<E> parent(Position<E> p) throws IllegalArgumentException;
|
||||
Iterable<Position<E>> children(Position<E> p) throws IllegalArgumentException;
|
||||
int numChildren(Position<E> p) throws IllegalArgumentException;
|
||||
boolean isInternal(Position<E> p) throws IllegalArgumentException;
|
||||
boolean isExternal(Position<E> p) throws IllegalArgumentException;
|
||||
boolean isRoot(Position<E> p) throws IllegalArgumentException;
|
||||
int size();
|
||||
boolean isEmpty();
|
||||
Iterator<E> iterator();
|
||||
Iterable<Position<E>> positions();
|
||||
}
|
6
README.md
Normal file
6
README.md
Normal file
|
@ -0,0 +1,6 @@
|
|||
# CS2 java projects
|
||||
|
||||
This repository is simply a record of the projects I did for my Computer Science 2 class.
|
||||
As I didnt come up with the bright idea to put this in a git repository until after im halfway through Computer Science 2, the inital commits will contain the first 7 labs, and later commits will be the other labs.
|
||||
|
||||
Feel free to look around, but keep in mind, as this was a data structures course, we were only rarely allowed to use built in java libraries, and built our own data structures from scratch.
|
68
Recursion/Recursion/src/Client.java
Normal file
68
Recursion/Recursion/src/Client.java
Normal file
|
@ -0,0 +1,68 @@
|
|||
|
||||
public class Client {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// example1();
|
||||
|
||||
// example2();
|
||||
|
||||
example3();
|
||||
|
||||
// example4();
|
||||
|
||||
// example5();
|
||||
|
||||
// example6();
|
||||
}
|
||||
|
||||
public static void example1()
|
||||
{
|
||||
int num = 5;
|
||||
|
||||
System.out.println("Factiorial( " + num + " ) = " + Recursion.factorial1( num ) );
|
||||
}
|
||||
|
||||
public static void example2( )
|
||||
{
|
||||
int num = 5;
|
||||
|
||||
Recursion.factorial2( num , 0 );
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void example3( )
|
||||
{
|
||||
for ( int i = 0; i < 14; i++ )
|
||||
{
|
||||
System.out.printf("Factiorial( %2d ) = %,15d\n", i, Recursion.factorial1( i ) );
|
||||
}
|
||||
}
|
||||
|
||||
public static void example4( )
|
||||
{
|
||||
for ( int i = 0; i < 20; i++ )
|
||||
{
|
||||
System.out.printf("Factiorial( %2d ) = %,15d\n", i, Recursion.factorial1( i ) );
|
||||
}
|
||||
}
|
||||
|
||||
public static void example5( )
|
||||
{
|
||||
for ( long i = 0; i < 25; i++ )
|
||||
{
|
||||
System.out.printf("FactiorialL( %2d ) = %,30d\n", i, Recursion.factorialL( i ) );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void example6( )
|
||||
{
|
||||
for ( long i = 0; i < 100000; i++ )
|
||||
{
|
||||
System.out.printf("FactiorialL( %2d ) = %,30d\n", i, Recursion.factorialL( i ) );
|
||||
}
|
||||
}
|
||||
}
|
46
Recursion/Recursion/src/Recursion.java
Normal file
46
Recursion/Recursion/src/Recursion.java
Normal file
|
@ -0,0 +1,46 @@
|
|||
|
||||
public class Recursion {
|
||||
|
||||
public static int factorial1( int i )
|
||||
{
|
||||
if ( i < 1 )
|
||||
return 1;
|
||||
else
|
||||
return i * factorial1( i - 1 );
|
||||
}
|
||||
|
||||
public static int factorial2( int i, int level )
|
||||
{
|
||||
System.out.println( indent(level) + ">>> factorial( " + i + " )" );
|
||||
if ( i < 1 )
|
||||
{
|
||||
System.out.println( indent(level) + "<<< 1 (the base case)" );
|
||||
return 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
int returnValue = factorial2( i - 1, level + 1 );
|
||||
int answer = i * returnValue;
|
||||
System.out.println( indent(level) + "<<< " + answer + " = " + i + " * " + returnValue );
|
||||
return i * returnValue;
|
||||
}
|
||||
}
|
||||
|
||||
public static String indent( int level )
|
||||
{
|
||||
String returnString = "";
|
||||
for ( int i = 0; i < level; i++ )
|
||||
returnString += " ";
|
||||
return returnString;
|
||||
}
|
||||
|
||||
public static long factorialL( long i )
|
||||
{
|
||||
if ( i < 1 )
|
||||
return 1;
|
||||
else
|
||||
{
|
||||
return i * factorialL( i - 1 );
|
||||
}
|
||||
}
|
||||
}
|
Reference in a new issue