Aggiunti alcuni esercizi

This commit is contained in:
2014-06-03 23:12:17 +02:00
parent 01c626d0e0
commit 7f2845fe2d
32 changed files with 1719 additions and 330 deletions

View File

@@ -1,22 +0,0 @@
package com.xgiovio;
import position.NodePositionList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
NodePositionList<Integer> a = new NodePositionList<Integer>();
a.addLast(1);
a.addLast(2);
Iterator<Integer> it = a.iterator();
a.addLast(3);
a.addLast(4);
for (;it.hasNext();)
System.out.println(it.next());
}
}

View File

@@ -2,6 +2,7 @@ package com.xgiovio;
import com.xgiovio.general_utility.test_object;
import sequence.NodeSequence;
import com.xgiovio.esercizi.*;
/**
* Created with xgiovio.macbookair.
@@ -52,7 +53,7 @@ public class NodeSequenceTest {
a.set(6,new test_object(200));
System.out.print(a);
global.reverse(a);
static_methods.reverse(a);
System.out.print(a);

View File

@@ -0,0 +1,205 @@
package com.xgiovio.esercizi;
import dictionary.Dictionary;
import exceptions.InvalidEntryException;
import exceptions.InvalidKeyException;
import position.NodePositionList;
import position.Position;
import position.PositionList;
import priorityqueue.Entry;
import tree.binarytree.LinkedBinaryTree;
import utility.DefaultComparator;
import java.util.Comparator;
public class BinarySearchTreeWithOtherMethods<K,V> extends LinkedBinaryTree<Entry<K,V>> implements Dictionary<K,V> {
protected Comparator<K> C; // comparator
protected Position<Entry<K,V>> actionPos; // insert node or removed node's parent
protected int numEntries = 0; // number of entries
public BinarySearchTreeWithOtherMethods() {
C = new DefaultComparator<K>();
addRoot(null);
}
public BinarySearchTreeWithOtherMethods(Comparator<K> c) {
C = c;
addRoot(null);
}
/** Nested class for location-aware binary search tree entries */
protected static class BSTEntry<K,V> implements Entry<K,V> {
protected K key;
protected V value;
protected Position<Entry<K,V>> pos;
BSTEntry(K k, V v, Position<Entry<K,V>> p) {
key = k; value = v; pos = p;
}
public K getKey() { return key; }
public V getValue() { return value; }
public Position<Entry<K,V>> position() { return pos; }
}
/** Extracts the key of the entry at a given node of the tree. */
protected K key(Position<Entry<K,V>> position) {
return position.element().getKey();
}
/** Extracts the value of the entry at a given node of the tree. */
protected V value(Position<Entry<K,V>> position) {
return position.element().getValue();
}
/** Extracts the entry at a given node of the tree. */
protected Entry<K,V> entry(Position<Entry<K,V>> position) {
return position.element();
}
/** Replaces an entry with a new entry (and reset the entry's location) */
protected void replaceEntry(Position <Entry<K,V>> pos, Entry<K,V> ent) {
((BSTEntry<K,V>) ent).pos = pos;
replace(pos, ent);
}
protected void checkKey(K key) throws InvalidKeyException {
if(key == null)
throw new InvalidKeyException("null key");
}
protected void checkEntry(Entry<K,V> ent) throws InvalidEntryException {
if(ent == null || !(ent instanceof BSTEntry))
throw new InvalidEntryException("invalid entry");
}
protected Entry<K,V> insertAtExternal(Position<Entry<K,V>> v, Entry<K,V> e) {
expandExternal(v,null,null);
replace(v, e);
numEntries++;
return e;
}
/** Auxiliary method for removing an external node and its parent */
protected void removeExternal(Position<Entry<K,V>> v) {
removeAboveExternal(v);
numEntries--;
}
/** Auxiliary method used by find, insert, and remove. */
protected Position<Entry<K,V>> treeSearch(K key, Position<Entry<K,V>> pos) {
if (isExternal(pos)) return pos; // key not found; return external node
else {
K curKey = key(pos);
int comp = C.compare(key, curKey);
if (comp < 0)
return treeSearch(key, left(pos)); // search left subtree
else if (comp > 0)
return treeSearch(key, right(pos)); // search right subtree
return pos; // return internal node where key is found
}
}
// Adds to L all entries in the subtree rooted at v having keys equal to k
protected void addAll(PositionList<Entry<K,V>> L, Position<Entry<K,V>> v, K k) {
if (isExternal(v)) return;
Position<Entry<K,V>> pos = treeSearch(k, v);
if (!isExternal(pos)) { // we found an entry with key equal to k
addAll(L, left(pos), k);
L.addLast(pos.element()); // add entries in inorder
addAll(L, right(pos), k);
} // this recursive algorithm is simple, but it's not the fastest
}
/** Returns the number of entries in the tree. */
public int size() { return numEntries; }
/** Returns whether the tree is empty. */
public boolean isEmpty() { return size() == 0; }
/** Returns an entry containing the given key. Returns null if no such entry exists. */
public Entry<K,V> find(K key) throws InvalidKeyException {
checkKey(key); // may throw an InvalidKeyException
Position<Entry<K,V>> curPos = treeSearch(key, root());
actionPos = curPos; // node where the search ended
if (isInternal(curPos)) return entry(curPos);
return null;
}
/** Returns an iterable collection of all the entries containing the given key. */
public Iterable<Entry<K,V>> findAll(K key) throws InvalidKeyException {
checkKey(key); // may throw an InvalidKeyException
PositionList<Entry<K,V>> L = new NodePositionList<Entry<K,V>>();
addAll(L, root(), key);
return L;
}
/** Inserts an entry into the tree and returns the newly created entry. */
public Entry<K,V> insert(K k, V x) throws InvalidKeyException {
checkKey(k); // may throw an InvalidKeyException
Position<Entry<K,V>> insPos = treeSearch(k, root());
while (!isExternal(insPos)) // iterative search for insertion position
insPos = treeSearch(k, left(insPos));
actionPos = insPos; // node where the new entry is being inserted
return insertAtExternal(insPos, new BSTEntry<K,V>(k, x, insPos));
}
/** Removes and returns a given entry. */
public Entry<K,V> remove(Entry<K,V> ent) throws InvalidEntryException {
checkEntry(ent); // may throw an InvalidEntryException
Position<Entry<K,V>> remPos = ((BSTEntry<K,V>) ent).position();
Entry<K,V> toReturn = entry(remPos); // entry to be returned
if (isExternal(left(remPos))) remPos = left(remPos); // left easy case
else if (isExternal(right(remPos))) remPos = right(remPos); // right easy case
else { // entry is at a node with internal children
Position<Entry<K,V>> swapPos = remPos; // find node for moving entry
remPos = right(swapPos);
do
remPos = left(remPos);
while (isInternal(remPos));
replaceEntry(swapPos, (Entry<K,V>) parent(remPos).element());
}
actionPos = sibling(remPos); // sibling of the leaf to be removed
removeExternal(remPos);
return toReturn;
}
/** Returns an iterator containing all entries in the tree. */
public Iterable<Entry<K,V>> entries() {
PositionList<Entry<K,V>> entries = new NodePositionList<Entry<K,V>>();
Iterable<Position<Entry<K,V>>> positer = positions();
for (Position<Entry<K,V>> cur: positer)
if (isInternal(cur))
entries.addLast(cur.element());
return entries;
}
protected class Integer_Wrapper{
public int value = 0;
}
public Iterable <V> withSmallestKeys(int k){
PositionList<V> to_return = new NodePositionList<V>();
Integer_Wrapper counter = new Integer_Wrapper();
exec_withSmallestKeys (k,counter,root(),to_return);
return to_return;
}
protected void exec_withSmallestKeys (int k,Integer_Wrapper counter, Position<Entry<K,V>> p, PositionList<V> l ){
if (isInternal(left(p))){
exec_withSmallestKeys(k,counter,left(p),l);
}
if (counter.value < k) {
l.addLast(p.element().getValue());
counter.value++;
}
if (counter.value < k && isInternal(right(p)) ) {
exec_withSmallestKeys(k,counter,right(p),l);
}
}
}

View File

@@ -0,0 +1,159 @@
package com.xgiovio.esercizi;
import exceptions.InvalidEntryException;
import exceptions.InvalidKeyException;
import position.NodePositionList;
import position.Position;
import position.PositionList;
import priorityqueue.AdaptablePriorityQueue;
import priorityqueue.Entry;
import priorityqueue.MyEntry;
import priorityqueue.heap.HeapPriorityQueue;
import java.util.Comparator;
/**
* Created with MONSTER.
* User: xgiovio
* Date: 11/05/2014
* Time: 14:55
*/
public class HeapAdaptablePriorityQueueWithOtherMethods<K,V> extends HeapPriorityQueue<K,V> implements AdaptablePriorityQueue<K,V> {
public HeapAdaptablePriorityQueueWithOtherMethods() {
super();
}
public HeapAdaptablePriorityQueueWithOtherMethods(Comparator comp) {
super(comp);
}
//override from parent class
public Entry<K,V> insert (K k, V v) throws InvalidKeyException {
checkKey(k);
LocationAwareEntry<K,V> entry = new LocationAwareEntry<K,V>(k,v);
Position <Entry<K,V>> z = heap.add(entry);
entry.setLocation(z);
upHeap(z);
return entry;
}
protected void swap(Position<Entry<K,V>> u,Position<Entry<K,V>> v) {
super.swap(u,v);
getEntry(u).setLocation(u);
getEntry(v).setLocation(v);
}
//end override from parent class
public Entry<K,V> remove(Entry<K,V> entry) throws InvalidEntryException {
LocationAwareEntry<K,V> ee = checkEntry(entry);
Position < Entry<K,V>> p = ee.location();
if(size() == 1)
return (Entry<K,V>) heap.remove();
replaceEntry(p,(LocationAwareEntry<K,V>)heap.remove());
upHeap(p);
downHeap(p);
ee.setLocation(null);
return ee;
}
public K replaceKey(Entry<K,V> entry, K k) throws InvalidEntryException,InvalidKeyException
{
checkKey(k);
LocationAwareEntry<K,V> ee = checkEntry(entry);
K oldKey = ee.setKey(k);
upHeap(ee.location());
downHeap(ee.location());
return oldKey;
}
public V replaceValue(Entry<K,V> e, V value) throws InvalidEntryException
{
LocationAwareEntry<K,V> ee = checkEntry(e);
return ee.setValue(value);
}
//auxiliar
protected Position< Entry<K,V>> replaceEntry(Position<Entry<K,V>> v, LocationAwareEntry<K,V> e) {
heap.replace(v,e);
return e.setLocation(v);
}
protected LocationAwareEntry<K,V> getEntry(Position <Entry<K,V> >p) {
return (LocationAwareEntry<K,V>) p.element();
}
protected LocationAwareEntry<K,V> checkEntry(Entry<K,V> e) throws InvalidEntryException
{
if(e == null || !(e instanceof LocationAwareEntry) || isEmpty() )
throw new InvalidEntryException("entrata non valida");
return (LocationAwareEntry) e;
}
// inner class
protected static class LocationAwareEntry<K,V> extends MyEntry<K,V> {
protected Position<Entry<K, V>> loc = null;
public LocationAwareEntry(K k, V v) {
super(k, v);
}
public LocationAwareEntry(K k, V v, Position pos) {
super(k, v);
loc = pos;
}
protected Position < Entry<K,V>> location() {
return loc;
}
protected Position < Entry<K,V> >setLocation(Position< Entry<K,V>> pos) {
Position <Entry<K,V>> oldPosition = location();
loc = pos;
return oldPosition;
}
protected K setKey(K k) {
K oldKey = getKey();
key = k;
return oldKey;
}
protected V setValue(V v) {
V oldValue = getValue();
value = v;
return oldValue;
}
public String toString() { return "(" + key + "," + value + ")"; }
}
public String toString() {
return super.toString();
}
public Iterable <Position<Entry<K,V>>> insertEntries(K[ ] S1,V[ ]S2) {
PositionList<Position<Entry<K,V>>> to_return = new NodePositionList<Position<Entry<K, V>>>();
for (int i = 0; i< S1.length ; i++ ){
to_return.addLast (((LocationAwareEntry<K,V>)(insert(S1[i],S2[i]))).location());
}
return to_return;
}
}

View File

@@ -0,0 +1,359 @@
package com.xgiovio.esercizi;
import exceptions.BoundaryViolationException;
import exceptions.EmptyTreeException;
import exceptions.InvalidPositionException;
import exceptions.NonEmptyTreeException;
import position.NodePositionList;
import position.Position;
import position.PositionList;
import tree.binarytree.BTNode;
import tree.binarytree.BTPosition;
import tree.binarytree.BinaryTree;
import java.util.Iterator;
public class LinkedBinaryTreeWithOtherMethods<E> implements BinaryTree<E> {
protected BTPosition<E> root;
protected int size;
public LinkedBinaryTreeWithOtherMethods() {
root = null;
size = 0;
}
public int size() {
return size;
}
public boolean isEmpty() {
return (size == 0);
}
public boolean isInternal(Position<E> v) throws InvalidPositionException {
checkPosition(v);
return (hasLeft(v) || hasRight(v));
}
public boolean isExternal(Position<E> v) throws InvalidPositionException {
return !isInternal(v);
}
public boolean isRoot(Position<E> v) throws InvalidPositionException {
checkPosition(v);
return (v == root());
}
public boolean hasLeft(Position<E> v) throws InvalidPositionException {
BTPosition<E> vv = checkPosition(v);
return (vv.getLeft() != null);
}
public boolean hasRight(Position<E> v) throws InvalidPositionException {
BTPosition<E> vv = checkPosition(v);
return (vv.getRight() != null);
}
public Position<E> root() throws EmptyTreeException {
if (root == null)
throw new EmptyTreeException("The tree is empty");
return root;
}
public Position<E> left(Position<E> v) throws InvalidPositionException, BoundaryViolationException {
BTPosition<E> vv = checkPosition(v);
Position<E> leftPos = vv.getLeft();
if (leftPos == null)
throw new BoundaryViolationException("No left child");
return leftPos;
}
public Position<E> right(Position<E> v)
throws InvalidPositionException, BoundaryViolationException {
BTPosition<E> vv = checkPosition(v);
Position<E> rightPos = vv.getRight();
if (rightPos == null)
throw new BoundaryViolationException("No right child");
return rightPos;
}
public Position<E> parent(Position<E> v) throws InvalidPositionException, BoundaryViolationException {
BTPosition<E> vv = checkPosition(v);
Position<E> parentPos = vv.getParent();
if (parentPos == null)
throw new BoundaryViolationException("No parent");
return parentPos;
}
public Iterable<Position<E>> children(Position<E> v) throws InvalidPositionException {
PositionList<Position<E>> children = new NodePositionList<Position<E>>();
if (hasLeft(v))
children.addLast(left(v));
if (hasRight(v))
children.addLast(right(v));
return children;
}
public Iterable<Position<E>> positions() {
PositionList<Position<E>> positions = new NodePositionList<Position<E>>();
if(size != 0)
preorderPositions(root(), positions);
return positions;
}
public Iterator<E> iterator() {
Iterable<Position<E>> positions = positions();
PositionList<E> elements = new NodePositionList<E>();
for (Position<E> pos: positions)
elements.addLast(pos.element());
return elements.iterator();
}
public E replace(Position<E> v, E o) throws InvalidPositionException {
BTPosition<E> vv = checkPosition(v);
E temp = v.element();
vv.setElement(o);
return temp;
}
public Position<E> sibling(Position<E> v) throws InvalidPositionException, BoundaryViolationException {
BTPosition<E> vv = checkPosition(v);
BTPosition<E> parentPos = vv.getParent();
if (parentPos != null) {
BTPosition<E> sibPos;
BTPosition<E> leftPos = parentPos.getLeft();
if (leftPos == vv)
sibPos = parentPos.getRight();
else
sibPos = parentPos.getLeft();
if (sibPos != null)
return sibPos;
}
throw new BoundaryViolationException("No sibling");
}
public Position<E> addRoot(E e) throws NonEmptyTreeException {
if(!isEmpty())
throw new NonEmptyTreeException("Tree already has a root");
size = 1;
root = createNode(e,null,null,null);
return root;
}
public Position<E> insertLeft(Position<E> v, E e) throws InvalidPositionException {
BTPosition<E> vv = checkPosition(v);
Position<E> leftPos = vv.getLeft();
if (leftPos != null)
throw new InvalidPositionException("Node already has a left child");
BTPosition<E> ww = createNode(e, vv, null, null);
vv.setLeft(ww);
size++;
return ww;
}
public Position<E> insertRight(Position<E> v, E e) throws InvalidPositionException {
BTPosition<E> vv = checkPosition(v);
Position<E> rightPos = vv.getRight();
if (rightPos != null)
throw new InvalidPositionException("Node already has a right child");
BTPosition<E> w = createNode(e, vv, null, null);
vv.setRight(w);
size++;
return w;
}
public E remove(Position<E> v) throws InvalidPositionException {
BTPosition<E> vv = checkPosition(v);
BTPosition<E> leftPos = vv.getLeft();
BTPosition<E> rightPos = vv.getRight();
if (leftPos != null && rightPos != null)
throw new InvalidPositionException("Cannot remove node with two children");
BTPosition<E> ww;
if (leftPos != null)
ww = leftPos;
else if (rightPos != null)
ww = rightPos;
else
ww = null;
if (vv == root) {
if (ww != null)
ww.setParent(null);
root = ww;
}
else {
BTPosition<E> uu = vv.getParent();
if (vv == uu.getLeft())
uu.setLeft(ww);
else
uu.setRight(ww);
if(ww != null)
ww.setParent(uu);
}
size--;
return v.element();
}
/** Attaches two trees to be subtrees of an external node. */
public void attach(Position<E> v, BinaryTree<E> T1, BinaryTree<E> T2) throws InvalidPositionException {
BTPosition<E> vv = checkPosition(v);
if (isInternal(v))
throw new InvalidPositionException("Cannot attach from internal node");
int newSize = size + T1.size() + T2.size();
if (!T1.isEmpty()) {
BTPosition<E> r1 = checkPosition(T1.root());
vv.setLeft(r1);
r1.setParent(vv);
}
if (!T2.isEmpty()) {
BTPosition<E> r2 = checkPosition(T2.root());
vv.setRight(r2);
r2.setParent(vv);
}
size = newSize;
}
public void swapElements(Position<E> v, Position<E> w) throws InvalidPositionException {
BTPosition<E> vv = checkPosition(v);
BTPosition<E> ww = checkPosition(w);
E temp = w.element();
ww.setElement(v.element());
vv.setElement(temp);
}
public void expandExternal(Position<E> v, E l, E r) throws InvalidPositionException {
checkPosition(v);
if (!isExternal(v))
throw new InvalidPositionException("Node is not external");
insertLeft(v, l);
insertRight(v, r);
}
public void removeAboveExternal(Position<E> v) throws InvalidPositionException {
checkPosition(v);
if (!isExternal(v))
throw new InvalidPositionException("Node is not external");
if (isRoot(v))
remove(v);
else {
Position<E> u = parent(v);
remove(v);
remove(u);
}
}
public void attachLeaves (PositionList<E> L) {
if (!isEmpty())
attachLeaves_r(root(),L);
}
protected void attachLeaves_r(Position<E> v, PositionList<E> L) throws InvalidPositionException {
BTPosition<E>vv = checkPosition(v);
if (hasLeft(v))
attachLeaves_r(left(v), L);
if (hasRight(v))
attachLeaves_r(right(v), L);
if (isExternal(v)){
BTPosition<E> a = createNode( L.remove(L.first()) ,vv,null,null);
BTPosition<E> b = createNode( L.remove(L.first()) ,vv,null,null);
vv.setLeft(a);
vv.setRight(b);
size+=2;
}
}
// Other methods
protected BTPosition<E> checkPosition(Position<E> v) throws InvalidPositionException {
if (v == null || !(v instanceof BTPosition) || isEmpty() )
throw new InvalidPositionException("The position is invalid");
return (BTPosition<E>) v;
}
protected BTPosition<E> createNode(E element, BTPosition<E> parent, BTPosition<E> left, BTPosition<E> right) {
return new BTNode<E>(element,parent,left,right); }
protected void preorderPositions(Position<E> v, PositionList<Position<E>> pos) throws InvalidPositionException {
pos.addLast(v);
if (hasLeft(v))
preorderPositions(left(v), pos);
if (hasRight(v))
preorderPositions(right(v), pos);
}
protected void inorderPositions(Position<E> v, PositionList<Position<E>> pos) throws InvalidPositionException {
if (hasLeft(v))
inorderPositions(left(v), pos);
pos.addLast(v);
if (hasRight(v))
inorderPositions(right(v), pos);
}
protected void postorderPositions(Position<E> v, PositionList<Position<E>> pos) throws InvalidPositionException {
if (hasLeft(v))
inorderPositions(left(v), pos);
if (hasRight(v))
inorderPositions(right(v), pos);
pos.addLast(v);
}
public String toString() {
String to_return = "";
to_return = to_return + "[";
if (size() == 0 )
return to_return+= "]";
NodePositionList<Position<E>> t = new NodePositionList<Position<E>>();
postorderPositions(root(),t);
for (Position<E> w :t){
to_return+=w.element() + ",";
}
to_return = to_return.substring(0, to_return.length()-1);
return to_return+= "]";
}
public void attachLeaves() {
if (size() > 1)
exec_attachLeaves (root());
}
protected void exec_attachLeaves (Position<E> p) {
BTPosition<E> pp = (BTPosition<E>) p;
if (isInternal(p)){
if(pp.getLeft() == null )
pp.setLeft(createNode(null,pp,null,null));
else
exec_attachLeaves(pp.getLeft());
if(pp.getRight() == null )
pp.setRight(createNode(null,pp,null,null));
else
exec_attachLeaves(pp.getRight());
}
}
}

View File

@@ -0,0 +1,277 @@
package com.xgiovio.esercizi;
import exceptions.*;
import position.NodePositionList;
import position.Position;
import position.PositionList;
import tree.Tree;
import tree.TreeNode;
import tree.TreePosition;
import java.util.Iterator;
/**
* Created with xgiovio.macbookair.
* User: xgiovio
* Date: 07/04/14
* Time: 15:45
*/
public class LinkedTreeWithOtherMethods<E> implements Tree<E> {
protected TreePosition<E> root = null;
protected int size = 0;
public int size() {
return size;
}
public boolean isEmpty() {
return (size == 0);
}
public Iterable<Position<E>> positions() {
PositionList<Position<E>> positions = new NodePositionList<Position<E>>();
if(size != 0)
preorderPositions(root(), positions);
return positions;
}
public E replace(Position<E> v, E o) throws InvalidPositionException {
TreePosition<E> vv = checkPosition(v);
E temp = v.element();
vv.setElement(o);
return temp;
}
public Position<E> root() throws EmptyTreeException {
if (root == null)
throw new EmptyTreeException("The tree is empty");
return root;
}
public Position<E> parent(Position<E> v) throws InvalidPositionException, BoundaryViolationException {
TreePosition<E> vv = checkPosition(v);
Position<E> parentPos = vv.getParent();
if (parentPos == null)
throw new BoundaryViolationException("No parent");
return parentPos;
}
public Iterable<Position<E>> children(Position<E> v) throws InvalidPositionException {
TreePosition<E> vv = checkPosition(v);
if (isExternal(v))
throw new InvalidPositionException("External nodes have no children");
return vv.getChildren();
}
public boolean isInternal(Position<E> v) throws InvalidPositionException {
return !isExternal(v);
}
public boolean isExternal(Position<E> v) throws InvalidPositionException {
TreePosition<E> vv = checkPosition(v);
return vv.getChildren().isEmpty();
}
public boolean isRoot(Position<E> v) throws InvalidPositionException {
checkPosition(v);
return (v == root());
}
public Iterator<E> iterator() {
Iterable<Position<E>> positions = positions();
PositionList<E> elements = new NodePositionList<E>();
for (Position<E> pos: positions)
elements.addLast(pos.element());
return elements.iterator();
}
////////////////////////// help methods
protected void preorderPositions(Position<E> v, PositionList<Position<E>> pos) throws InvalidPositionException {
TreePosition<E> a = checkPosition(v);
pos.addLast(a);
for (Position<E> w : a.getChildren())
preorderPositions(w, pos);
}
protected void postorderPositions(Position<E> v, PositionList<Position<E>> pos) throws InvalidPositionException {
TreePosition<E> a = checkPosition(v);
for (Position<E> w : a.getChildren())
postorderPositions(w, pos);
pos.addLast(a);
}
protected TreePosition<E> checkPosition(Position<E> v)
throws InvalidPositionException {
if (v == null || !(v instanceof TreePosition) || isEmpty() )
throw new InvalidPositionException("The position is invalid");
return (TreePosition<E>) v;
}
public Position<E> addRoot(E e) throws NonEmptyTreeException {
if(!isEmpty())
throw new NonEmptyTreeException("Tree already has a root");
size = 1;
root = createNode(e,null,null);
return root;
}
public void swapElements(Position<E> v, Position<E> w)
throws InvalidPositionException {
TreePosition<E> vv = checkPosition(v);
TreePosition<E> ww = checkPosition(w);
E temp = w.element();
ww.setElement(v.element());
vv.setElement(temp);
}
protected TreePosition<E> createNode(E element, TreePosition<E> parent, PositionList<Position<E>> children) {
return new TreeNode<E>(element,parent,children);
}
public E removeRoot() throws EmptyTreeException, UndeletableNodeException {
if (isEmpty())
throw new EmptyTreeException();
if (size() > 1)
throw new UndeletableNodeException();
E to_return = root().element();
root = null;
size = 0;
return to_return;
}
public E removeExternalChild(Position<E> v) throws UndeletableNodeException,InvalidPositionException{
TreePosition<E> a = checkPosition(v);
if (isExternal(a))
throw new InvalidPositionException();
PositionList<Position<E>> c = a.getChildren();
if (isInternal(c.first().element()))
throw new UndeletableNodeException();
E to_return = (c.remove(c.first())).element();
size--;
return to_return;
}
public Position <E> addChild (E e , Position<E> v) throws InvalidPositionException {
TreePosition<E> a = checkPosition(v);
a.getChildren().addLast(createNode(e,a,null));
size++;
return a.getChildren().last().element();
}
public E remove (Position<E> v) {
TreePosition<E> a = checkPosition(v);
if (isInternal(a))
throw new InvalidPositionException();
if (size() == 1)
return removeRoot();
PositionList<Position<E>> list = a.getParent().getChildren();
Iterable<Position<Position<E>>> it = list.positions();
for (Position<Position<E>> w : it){
if (w.element() == v){
size--;
return (list.remove(w)).element();
}
}
return null;
}
public int depth ( Position<E> v) throws InvalidPositionException{
TreePosition<E> a = checkPosition(v);
if (a.getParent() == null)
return 0;
return (depth(a.getParent()) + 1);
}
public int height () throws EmptyTreeException{
return height_f(root());
}
public int height_f ( Position<E> v) {
TreePosition<E> a = checkPosition(v);
if (isExternal(a))
return 0;
int max = 0;
for ( Position<E> w : a.getChildren()){
if (max == 0 || height_f(w) > max){
max = height_f(w);
}
}
return 1 + max;
}
@Override
public String toString() {
String to_return = "";
to_return = to_return + "[";
if (size() == 0 )
return to_return+= "]";
NodePositionList<Position<E>> t = new NodePositionList<Position<E>>();
postorderPositions(root(),t);
for (Position<E> w :t){
to_return+=w.element() + ",";
}
to_return = to_return.substring(0, to_return.length()-1);
return to_return+= "]";
}
public int arity () {
if (size() <= 1) return 0;
return exec_arity (root());
}
protected int exec_arity (Position<E> v){
TreePosition<E> vv = checkPosition(v);
if (isExternal(v))
return 0;
PositionList<Position<E>> c = vv.getChildren();
int arity = c.size();
int max = arity;
for (Position<E> p : c){
max = max(exec_arity(p),max);
}
return max;
}
int max (int a, int b ){
if (a > b)
return a;
return b;
}
}

View File

@@ -0,0 +1,228 @@
package com.xgiovio.esercizi;
import dictionary.BinarySearchTree;
import position.NodePositionList;
import position.Position;
import position.PositionList;
import priorityqueue.Entry;
import set.OrderedListSet;
import set.Set;
import utility.DefaultComparator;
import utility.merge.MergeTemplate;
import java.util.Comparator;
import java.util.Iterator;
/**
* Created with xgiovio.macbookair.
* User: xgiovio
* Date: 14/05/14
* Time: 14:23
*/
public class OrderedListSetWithOtherMethods<E> implements Set<E> {
private Comparator<E> c;
private PositionList<E> L;
private Position<Set<E>> loc;
public OrderedListSetWithOtherMethods() {
L = new NodePositionList<E>();
c = new DefaultComparator<E>();
}
public OrderedListSetWithOtherMethods(Comparator<E> in_c) {
L = new NodePositionList<E>();
c = in_c;
}
public OrderedListSetWithOtherMethods(PositionList<E> in_l){
L = in_l;
c = new DefaultComparator<E>();
}
public OrderedListSetWithOtherMethods(PositionList<E> in_l, Comparator<E> in_c){
L = in_l;
c = in_c;
}
public OrderedListSetWithOtherMethods(E in_e, Comparator<E> in_c){
L = new NodePositionList<E>();
L.addLast(in_e);
c = in_c;
}
public OrderedListSetWithOtherMethods(E in_e){
L = new NodePositionList<E>();
L.addLast(in_e);
c = new DefaultComparator<E>();
}
public<V> OrderedListSetWithOtherMethods(Comparator <E> c, BinarySearchTree<E,V> D ) {
this.c = c;
L = new NodePositionList<E>();
if (!D.isEmpty()) {
L.addLast(D.root().element().getKey());
exec_OrderedListSetWithOtherMethods(D, D.root());
}
}
public <V> void exec_OrderedListSetWithOtherMethods (BinarySearchTree<E,V> D , Position<Entry<E,V>> p){
if (D.isInternal(D.left(p))) {
union(new OrderedListSetWithOtherMethods<E>(D.left(p).element().getKey()));
exec_OrderedListSetWithOtherMethods(D, D.left(p));
}
if (D.isInternal(D.right(p))) {
union(new OrderedListSetWithOtherMethods<E>(D.right(p).element().getKey()));
exec_OrderedListSetWithOtherMethods(D, D.right(p));
}
}
@Override
public int size() {
return L.size();
}
@Override
public boolean isEmpty() {
return L.isEmpty();
}
@Override
public Set<E> union(Set<E> B) {
MergeUnion<E> ret = new MergeUnion<E>(L, ((OrderedListSetWithOtherMethods<E>)B).L , c );
L = ret.getResult();
return this;
}
@Override
public Set<E> intersect(Set<E> B) {
MergeIntersect<E> ret = new MergeIntersect<E>(L, ((OrderedListSetWithOtherMethods<E>)B).L , c );
L = ret.getResult();
return this;
}
@Override
public Set<E> subtract(Set<E> B) {
MergeSubtract<E> ret = new MergeSubtract<E>(L, ((OrderedListSetWithOtherMethods<E>)B).L , c );
L = ret.getResult();
return this;
}
@Override
public String toString() {
return L.toString();
}
public Set<E> fastUnion(Set<E> B){
OrderedListSetWithOtherMethods<E> BB = (OrderedListSetWithOtherMethods<E>) B;
Iterator<E> it = BB.L.iterator();
for (;it.hasNext();)
L.addLast(it.next());
return this;
}
public E fastInsert(E x) {
L.addLast(x);
return x;
}
public Position<Set<E>> location (){
return loc;
}
public void setLocation (Position<Set<E>> in){
loc = in;
}
public PositionList<E> list (){
return L;
}
//////////////////////// inner class override methods from merge template /////
protected class MergeUnion<E> extends MergeTemplate<E>{
public MergeUnion (PositionList<E> A , PositionList<E> B, Comparator<E> c){
super(A,B,c);
}
@Override
protected void aIsLess(E a) {
s.addLast(a);
}
@Override
protected void bIsLess(E b) {
s.addLast(b);
}
@Override
protected void bothAreEqual(E a, E b) {
s.addLast(a);
}
}
protected class MergeIntersect<E> extends MergeTemplate<E>{
public MergeIntersect (PositionList<E> A , PositionList<E> B, Comparator<E> c){
super(A,B,c);
}
@Override
protected void aIsLess(E a) {
}
@Override
protected void bIsLess(E b) {
}
@Override
protected void bothAreEqual(E a, E b) {
s.addLast(a);
}
}
protected class MergeSubtract<E> extends MergeTemplate<E>{
public MergeSubtract (PositionList<E> A , PositionList<E> B, Comparator<E> c){
super(A,B,c);
}
@Override
protected void aIsLess(E a) {
s.addLast(a);
}
@Override
protected void bIsLess(E b) {
}
@Override
protected void bothAreEqual(E a, E b) {
}
}
}

View File

@@ -0,0 +1,45 @@
package com.xgiovio.esercizi;
import exceptions.EmptyStackException;
import priorityqueue.PriorityQueue;
import priorityqueue.heap.HeapPriorityQueue;
import stack.Stack;
/**
* Created with MONSTER.
* User: xgiovio
* Date: 03/06/2014
* Time: 13:50
*/
public class PQStack<E> implements Stack<E> {
private int priority = 0;
private PriorityQueue<Integer,E> p = new HeapPriorityQueue<Integer, E>();
@Override
public void push(E element) {
priority--;
p.insert(priority,element);
}
@Override
public E top() throws EmptyStackException {
return p.min().getValue();
}
@Override
public E pop() throws EmptyStackException {
return p.removeMin().getValue();
}
@Override
public boolean isEmpty() {
return (size()== 0);
}
@Override
public int size() {
return p.size();
}
}

View File

@@ -1,4 +1,4 @@
package esercizi;
package com.xgiovio.esercizi;
import exceptions.EmptyStackException;
import queue.NodeQueue;

View File

@@ -1,8 +1,7 @@
package esercizi;
package com.xgiovio.esercizi;
import exceptions.EmptyQueueException;
import queue.Queue;
import sequence.ArraySequence;
import stack.ArrayStack;
/**

View File

@@ -1,4 +1,4 @@
package com.xgiovio;
package com.xgiovio.esercizi;
import exceptions.EmptyStackException;
import stack.NodeStack;

View File

@@ -1,4 +1,4 @@
package com.xgiovio;
package com.xgiovio.esercizi;
import stack.NodeStack;

View File

@@ -1,4 +1,4 @@
package esercizi;
package com.xgiovio.esercizi;
/**
* Created with MONSTER.
@@ -6,7 +6,7 @@ package esercizi;
* Date: 13/04/2014
* Time: 22:18
*/
public class start {
public class start_static_methods {
public static void main(String[] args) {

View File

@@ -0,0 +1,419 @@
package com.xgiovio.esercizi;
import dictionary.Dictionary;
import map.ListMap;
import map.Map;
import position.NodePositionList;
import position.Position;
import position.PositionList;
import priorityqueue.Entry;
import priorityqueue.PriorityQueue;
import priorityqueue.SortedListPriorityQueue;
import priorityqueue.heap.HeapPriorityQueue;
import queue.NodeQueue;
import queue.Queue;
import sequence.Sequence;
import stack.ArrayStack;
import exceptions.*;
import tree.Tree;
import java.util.Comparator;
/**
* Created with MONSTER.
* User: xgiovio
* Date: 13/04/2014
* Time: 22:19
*/
public class static_methods {
// inver a string using a stack
public static String inverti (String s){
ArrayStack<Character> a = new ArrayStack<Character>();
for (int i = 0 ;i< s.length();i++){
a.push(s.charAt(i));
}
String to_return = "";
for (int i = 0 ;i< s.length();i++){
to_return += a.pop();
}
return to_return;
}
// verify is a string of [ and ( is correct using a stack
public static boolean checkParentheses (String s) {
ArrayStack<Character> a = new ArrayStack<Character>();
for (int i = 0 ; i< s.length();i++){
if (s.charAt(i) == '('){
a.push(s.charAt(i));
continue;
}
if (s.charAt(i) == ')'){
if (a.isEmpty() || a.top() != '('){
return false;
} else {
a.pop();
}
continue;
}
if (s.charAt(i) == '['){
if ( a.isEmpty() || a.top() != '(') {
a.push(s.charAt(i));
} else {
return false;
}
continue;
}
if (s.charAt(i) == ']'){
if (a.isEmpty() || a.top() != '['){
return false;
} else {
a.pop();
}
continue;
}
}
if (a.isEmpty()){
return true;
}else {
return false;
}
}
// verify is a string is palindrome using a stack
public static boolean isPalindrome (String s){
ArrayStack<Character> a = new ArrayStack<Character>();
if (s.length() < 2){
return true;
}else {
boolean pari;
if (s.length() % 2 == 0) {
pari = true;
} else {
pari = false;
}
for (int i= 0 ;i < s.length();i++){
if (!pari){
if (i <= s.length()/2){
a.push(s.charAt(i));
if (i == s.length()/2 ){
a.pop();
}
continue;
}
} else {
if (i <= (s.length()/2) -1){
a.push(s.charAt(i));
continue;
}
}
if (s.charAt(i) != a.pop()){
return false;
}
}
return true;
}
}
// extract the k element from a Queue Q. k should be >= 0
public static Integer extract (Queue<Integer> Q, int k) throws NotEnoughElements {
if (Q.size() <= k) {
throw new NotEnoughElements();
} else {
Integer t = null ;
for (int i = 0 ;i< Q.size();i++){
if (i == k){
t = Q.front();
}
Q.enqueue(Q.dequeue());
}
return t;
}
}
// invert a Queue without recursive methods
public static <E> void reverse (Queue<E> Q){
NodeQueue<E> newq = new NodeQueue<E>();
for (;Q.size()> 0;){
for (int i = 0;i< Q.size() - 1;i++){
Q.enqueue(Q.dequeue());
}
newq.enqueue(Q.dequeue());
}
int size = newq.size();
for (int i = 0;i<size;i++){
Q.enqueue(newq.dequeue());
}
}
// invert a Queue with recursion
public static <E> void recReverse (Queue<E> Q){
if (Q.size()>1){
E t = Q.dequeue();
recReverse(Q);
Q.enqueue(t);
}
}
// search element x in Queue Q . WARNING THIS FUNCTION ALTER THE ORIGINAL QUEUE Q
public static <E> boolean isContained (Queue<E>Q,E x){
if (Q.size() > 0){
E t = Q.dequeue();
if (t==x){
return true;
}
else{
return isContained(Q,x);
}
}else {
return false;
}
}
public static <E > void reverse (Sequence<E> in){
if (in.size()> 1){
E t = in.removeFirst();
static_methods.reverse(in);
in.addLast(t);
}
}
public static void cancellaDuplicati (PositionList<Integer> L){
if (L.size() >=2){
Position<Integer> first;
Position<Integer> second;
first = L.first();
second = L.next(first);
for (;true;) {
if (first.element().equals(second.element())) {
L.remove(second);
if (first!= L.last()) {
second = L.next(first);
}else {
break;
}
} else {
first = second;
if (first!= L.last()) {
second = L.next(second);
}else {
break;
}
}
}
}
}
public static <E> Iterable<E> selectLeaves(Tree<E> T, int k ){
if (T.isEmpty()) throw new EmptyTreeException();
NodePositionList<E> to_return = new NodePositionList<E>();
if (T.size() == 1){
to_return.addLast(T.root().element());
} else {
exec_selectLeaves (T,k,T.root(),0,to_return);
}
return to_return;
}
public static <E> void exec_selectLeaves(Tree<E> T, int k, Position<E> p, int c_k, PositionList<E> list ){
c_k++;
Iterable<Position<E>> ite = T.children(p);
for (Position<E> t : ite){
if (c_k == k)
list.addLast(t.element());
else if (T.isInternal(t))
exec_selectLeaves (T,k,t,c_k,list);
}
}
public static <E> boolean isContained (Tree<E> T, E x ) {
if (T.isEmpty()) throw new EmptyTreeException();
return exec_isContained (T,T.root(),x);
}
public static <E> boolean exec_isContained (Tree<E> T, Position<E> p , E x ) {
if (p.element().equals(x)) return true;
if (T.isInternal(p)){
Iterable<Position<E>> ite = T.children(p);
for (Position<E> t : ite){
if(exec_isContained (T,t,x)) return true;
}
return false;
}
return false;
}
public static class Integer_Wrapper{
public Integer value = 0;
}
public static int sumAllNodes(Tree<Integer> T) {
Integer_Wrapper returned = new Integer_Wrapper();
exec_sumAllNodes(T, T.root(), returned);
return returned.value;
}
public static void exec_sumAllNodes(Tree<Integer> T, Position<Integer> p , Integer_Wrapper returned) {
returned.value += p.element();
if (T.isInternal(p)) {
Iterable<Position<Integer>> ite = T.children(p);
for (Position<Integer> t : ite) {
exec_sumAllNodes(T, t, returned);
}
}
}
public static <V> PriorityQueue<Integer,V> f( PriorityQueue<Integer,V> P, Comparator<V> cV ){
PriorityQueue<Integer,V> to_return = new HeapPriorityQueue<Integer, V>();
int flag = 0;
Integer key = null;
V value = null;
for (;P.size() > 0;){
Entry<Integer,V> e = P.removeMin();
if (flag == 0){
flag = 1;
key = e.getKey();
value = e.getValue();
} else {
if(e.getKey().equals(key)){
if (cV.compare(e.getValue(),value) < 0 ){
value = e.getValue();
}
} else {
to_return.insert(key,value);
key = e.getKey();
value = e.getValue();
}
}
}
to_return.insert(key,value);
return to_return;
}
public static <K,V> PositionList<Entry<K,V> > sort(SortedListPriorityQueue<K,V> Q1, SortedListPriorityQueue<K,V> Q2, Comparator <K> c){
PositionList<Entry<K,V>> to_return = new NodePositionList<Entry<K, V>>();
Entry<K,V> a = Q1.removeMin();
Entry<K,V> b = Q2.removeMin();
for (;;){
if (c.compare(a.getKey(),b.getKey()) < 0){
to_return.addLast(a);
if (!Q1.isEmpty()) {
a = Q1.removeMin();continue;
}else break;
}
if (c.compare(a.getKey(),b.getKey()) == 0){
to_return.addLast(a);
to_return.addLast(b);
if (!Q1.isEmpty() && !Q2.isEmpty() ) {
a = Q1.removeMin();
b = Q2.removeMin();
continue;
}else break;
}
if (c.compare(a.getKey(),b.getKey()) > 0){
to_return.addLast(b);
if (!Q2.isEmpty()) {
b = Q2.removeMin();continue;
}else break;
}
}
for (;!Q1.isEmpty();){
a = Q1.removeMin();
to_return.addLast(a);
}
for (;!Q2.isEmpty();){
b = Q2.removeMin();
to_return.addLast(b);
}
return to_return;
}
public static<K,V> Iterable<Entry<K,V>>sortValues ( Dictionary<K,V> D,Comparator<V> c ){
PriorityQueue<V,Entry<K,V>> h = new HeapPriorityQueue<V, Entry<K, V>>(c);
for ( Entry<K,V> e : D.entries() ){
h.insert(e.getValue(),e);
}
PositionList<Entry<K,V>> to_return = new NodePositionList<Entry<K, V>>();
for (;!h.isEmpty();){
to_return.addLast(h.removeMin().getValue());
}
return to_return;
}
public static <K,V> Iterable <K> subtract( Dictionary<K,V> D1, Dictionary<K,V> D2) {
Map<K,Object> m = new ListMap<K,Object>();
for ( Entry<K,V> e :D2.entries()){
for ( Entry<K,V> e1 :D1.findAll(e.getKey())){
m.put ( (D1.remove(e1)).getKey() , null );
}
}
return m.keys();
}
}

View File

@@ -1,58 +0,0 @@
package com.xgiovio;
import position.Position;
import position.PositionList;
import sequence.Sequence;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Created with MONSTER.
* User: xgiovio
* Date: 30/03/2014
* Time: 21:35
*/
class global {
public static <E > void reverse (Sequence<E> in){
if (in.size()> 1){
E t = in.removeFirst();
global.reverse(in);
in.addLast(t);
}
}
public static void cancellaDuplicati (PositionList<Integer>L){
if (L.size() >=2){
Position<Integer> first;
Position<Integer> second;
first = L.first();
second = L.next(first);
for (;true;) {
if (first.element().equals(second.element())) {
L.remove(second);
if (first!= L.last()) {
second = L.next(first);
}else {
break;
}
} else {
first = second;
if (first!= L.last()) {
second = L.next(second);
}else {
break;
}
}
}
}
}
}

View File

@@ -1,4 +1,4 @@
package test_2_prova_intercorso;
package com.xgiovio.test_2_prova_intercorso;
/*

View File

@@ -1,4 +1,4 @@
package test_2_prova_intercorso;
package com.xgiovio.test_2_prova_intercorso;
/*Il programma deve stampare :

View File

@@ -1,4 +1,4 @@
package test_2_prova_intercorso;
package com.xgiovio.test_2_prova_intercorso;
/*Il programma deve stampare (ovviamente le entrate di M e D possono essere stampate in un diverso ordine):
I test:
@@ -18,7 +18,6 @@ Dopo aver invocato addEntries su M e D, si ha M=< (90,49) (70,39) (50,29) (30,19
import dictionary.Dictionary;
import dictionary.LinearProbingHashTable;
import exceptions.InvalidKeyException;
import map.HashTableMap;
import map.Map;
import priorityqueue.Entry;

View File

@@ -1,4 +1,4 @@
package test_2_prova_intercorso;
package com.xgiovio.test_2_prova_intercorso;
import exceptions.*;
/*Il programma deve stampare (l'ordine in cui vengono stampate le entrate su ciascuna linea e` ininfluente):

View File

@@ -1,4 +1,4 @@
package test_2_prova_intercorso;
package com.xgiovio.test_2_prova_intercorso;
import exceptions.EmptyTreeException;

View File

@@ -1,9 +1,7 @@
package test_2_prova_intercorso;
package com.xgiovio.test_2_prova_intercorso;
import arraylist.ArrayIndexList;
import arraylist.IndexList;
import exceptions.InvalidKeyException;
import graph.ComponentsBFS;
import graph.Edge;
import graph.Graph;
import graph.Vertex;

View File

@@ -1,4 +1,4 @@
package test_prova_intercorso;
package com.xgiovio.test_prova_intercorso;
public class EmptyMyADT_Exception extends RuntimeException {

View File

@@ -1,4 +1,4 @@
package test_prova_intercorso;
package com.xgiovio.test_prova_intercorso;
import stack.ArrayStack;

View File

@@ -1,4 +1,4 @@
package test_prova_intercorso;
package com.xgiovio.test_prova_intercorso;
public interface MyADT<E>{

View File

@@ -1,4 +1,4 @@
package test_prova_intercorso;
package com.xgiovio.test_prova_intercorso;
import queue.NodeQueue;

View File

@@ -1,4 +1,4 @@
package test_prova_intercorso;
package com.xgiovio.test_prova_intercorso;
public class test {

View File

@@ -1,193 +0,0 @@
package esercizi;
import queue.NodeQueue;
import queue.Queue;
import stack.ArrayStack;
import exceptions.*;
/**
* Created with MONSTER.
* User: xgiovio
* Date: 13/04/2014
* Time: 22:19
*/
public class static_methods {
// inver a string using a stack
public static String inverti (String s){
ArrayStack<Character> a = new ArrayStack<Character>();
for (int i = 0 ;i< s.length();i++){
a.push(s.charAt(i));
}
String to_return = "";
for (int i = 0 ;i< s.length();i++){
to_return += a.pop();
}
return to_return;
}
// verify is a string of [ and ( is correct using a stack
public static boolean checkParentheses (String s) {
ArrayStack<Character> a = new ArrayStack<Character>();
for (int i = 0 ; i< s.length();i++){
if (s.charAt(i) == '('){
a.push(s.charAt(i));
continue;
}
if (s.charAt(i) == ')'){
if (a.isEmpty() || a.top() != '('){
return false;
} else {
a.pop();
}
continue;
}
if (s.charAt(i) == '['){
if ( a.isEmpty() || a.top() != '(') {
a.push(s.charAt(i));
} else {
return false;
}
continue;
}
if (s.charAt(i) == ']'){
if (a.isEmpty() || a.top() != '['){
return false;
} else {
a.pop();
}
continue;
}
}
if (a.isEmpty()){
return true;
}else {
return false;
}
}
// verify is a string is palindrome using a stack
public static boolean isPalindrome (String s){
ArrayStack<Character> a = new ArrayStack<Character>();
if (s.length() < 2){
return true;
}else {
boolean pari;
if (s.length() % 2 == 0) {
pari = true;
} else {
pari = false;
}
for (int i= 0 ;i < s.length();i++){
if (!pari){
if (i <= s.length()/2){
a.push(s.charAt(i));
if (i == s.length()/2 ){
a.pop();
}
continue;
}
} else {
if (i <= (s.length()/2) -1){
a.push(s.charAt(i));
continue;
}
}
if (s.charAt(i) != a.pop()){
return false;
}
}
return true;
}
}
// extract the k element from a Queue Q. k should be >= 0
public static Integer extract (Queue<Integer> Q, int k) throws NotEnoughElements {
if (Q.size() <= k) {
throw new NotEnoughElements();
} else {
Integer t = null ;
for (int i = 0 ;i< Q.size();i++){
if (i == k){
t = Q.front();
}
Q.enqueue(Q.dequeue());
}
return t;
}
}
// invert a Queue without recursive methods
public static <E> void reverse (Queue<E> Q){
NodeQueue<E> newq = new NodeQueue<E>();
for (;Q.size()> 0;){
for (int i = 0;i< Q.size() - 1;i++){
Q.enqueue(Q.dequeue());
}
newq.enqueue(Q.dequeue());
}
int size = newq.size();
for (int i = 0;i<size;i++){
Q.enqueue(newq.dequeue());
}
}
// invert a Queue with recursion
public static <E> void recReverse (Queue<E> Q){
if (Q.size()>1){
E t = Q.dequeue();
recReverse(Q);
Q.enqueue(t);
}
}
// search element x in Queue Q . WARNING THIS FUNCTION ALTER THE ORIGINAL QUEUE Q
public static <E> boolean isContained (Queue<E>Q,E x){
if (Q.size() > 0){
E t = Q.dequeue();
if (t==x){
return true;
}
else{
return isContained(Q,x);
}
}else {
return false;
}
}
}

View File

@@ -12,7 +12,7 @@ import exceptions.InvalidKeyException;
*/
public class DFS<V, E, I, R> {
protected Graph<V, E> graph; // The graph being traversed
protected Vertex<V> start; // The start vertex for the DFS
protected Vertex<V> start; // The start_static_methods vertex for the DFS
protected I info; // Information object passed to DFS
protected R visitResult; // The result of a recursive traversal call
protected static Object STATUS = new Object(); // The status attribute
@@ -22,7 +22,7 @@ public class DFS<V, E, I, R> {
/** Execute a depth first search traversal on graph g, starting
* from a start vertex s, passing in an information object (in) */
* from a start_static_methods vertex s, passing in an information object (in) */
public R execute(Graph<V, E> g, Vertex<V> s, I in) throws InvalidKeyException {
graph = g;
start = s;

View File

@@ -14,7 +14,7 @@ import java.security.InvalidKeyException;
* <p>To execute the algorithm, use the {@link
* #execute(Graph,Vertex,Object) execute} method, and then make
* subsequent calls to the {@link #getDist(Vertex) getDist} method to
* obtain the shortest distance from the start to any given vertex.
* obtain the shortest distance from the start_static_methods to any given vertex.
*
* @author Roberto Tamassia, Michael Goodrich, Eric Zamore
*/

View File

@@ -46,7 +46,7 @@ public class FindCycleDFS<V, E>
protected boolean isDone() { return done; }
public Iterable<Position> finalResult(Iterable<Position> r) {
// remove the vertices and edges from start to cycleStart
// remove the vertices and edges from start_static_methods to cycleStart
if (!cycle.isEmpty()) {
for (Position<Position> p: cycle.positions()) {
if (p.element() == cycleStart)

View File

@@ -5,11 +5,11 @@ import position.NodePositionList;
import position.Position;
import position.PositionList;
/** Class specializing DFS to find a path between a start vertex and a target
/** Class specializing DFS to find a path between a start_static_methods vertex and a target
* vertex. It assumes the target vertex is passed as the info object to the
* execute method. It returns an iterable list of the vertices and edges
* comprising the path from start to info. The returned path is empty if
* info is unreachable from start. */
* comprising the path from start_static_methods to info. The returned path is empty if
* info is unreachable from start_static_methods. */
public class FindPathDFS<V, E>
extends DFS<V, E, Vertex<V>, Iterable<Position>> {
protected PositionList<Position> path;
@@ -27,7 +27,7 @@ public class FindPathDFS<V, E>
}
protected void finishVisit(Vertex<V> v) {
path.remove(path.last()); // remove v from path
if(!path.isEmpty()) // if v is not the start vertex
if(!path.isEmpty()) // if v is not the start_static_methods vertex
path.remove(path.last()); // remove discovery edge into v from path
}
protected void traverseDiscovery(Edge<E> e, Vertex<V> from) {

View File

@@ -195,33 +195,6 @@ public class LinkedTree <E> implements Tree<E> {
return null;
}
public int depth ( Position<E> v) throws InvalidPositionException{
TreePosition<E> a = checkPosition(v);
if (a.getParent() == null)
return 0;
return (depth(a.getParent()) + 1);
}
public int height () throws EmptyTreeException{
return height_f(root());
}
public int height_f ( Position<E> v) {
TreePosition<E> a = checkPosition(v);
if (isExternal(a))
return 0;
int max = 0;
for ( Position<E> w : a.getChildren()){
if (max == 0 || height_f(w) > max){
max = height_f(w);
}
}
return 1 + max;
}
@Override
public String toString() {
String to_return = "";