Aggiunti alcuni esercizi
This commit is contained in:
@@ -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());
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
|
||||
205
com/xgiovio/esercizi/BinarySearchTreeWithOtherMethods.java
Normal file
205
com/xgiovio/esercizi/BinarySearchTreeWithOtherMethods.java
Normal 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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
359
com/xgiovio/esercizi/LinkedBinaryTreeWithOtherMethods.java
Normal file
359
com/xgiovio/esercizi/LinkedBinaryTreeWithOtherMethods.java
Normal 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());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
277
com/xgiovio/esercizi/LinkedTreeWithOtherMethods.java
Normal file
277
com/xgiovio/esercizi/LinkedTreeWithOtherMethods.java
Normal 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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
228
com/xgiovio/esercizi/OrderedListSetWithOtherMethods.java
Normal file
228
com/xgiovio/esercizi/OrderedListSetWithOtherMethods.java
Normal 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) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
45
com/xgiovio/esercizi/PQStack.java
Normal file
45
com/xgiovio/esercizi/PQStack.java
Normal 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();
|
||||
}
|
||||
}
|
||||
65
com/xgiovio/esercizi/QStack.java
Normal file
65
com/xgiovio/esercizi/QStack.java
Normal file
@@ -0,0 +1,65 @@
|
||||
package com.xgiovio.esercizi;
|
||||
|
||||
import exceptions.EmptyStackException;
|
||||
import queue.NodeQueue;
|
||||
import stack.Stack;
|
||||
|
||||
/**
|
||||
* Created with MONSTER.
|
||||
* User: xgiovio
|
||||
* Date: 13/04/2014
|
||||
* Time: 23:48
|
||||
*/
|
||||
|
||||
// emulate a stack with a queue
|
||||
public class QStack<E> implements Stack<E> {
|
||||
|
||||
NodeQueue<E> a = new NodeQueue<E>();
|
||||
|
||||
@Override
|
||||
public void push(E element) {
|
||||
a.enqueue(element);
|
||||
}
|
||||
|
||||
@Override
|
||||
public E top() throws EmptyStackException {
|
||||
if (a.isEmpty()){
|
||||
throw new EmptyStackException();
|
||||
}else {
|
||||
E t;
|
||||
for (int i = 0 ;i<a.size() - 1;i++){
|
||||
a.enqueue(a.dequeue());
|
||||
}
|
||||
t = a.front();
|
||||
a.enqueue(a.dequeue());
|
||||
return t;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public E pop() throws EmptyStackException {
|
||||
if (a.isEmpty()){
|
||||
throw new EmptyStackException();
|
||||
}else {
|
||||
for (int i = 0 ;i<a.size() - 1;i++){
|
||||
a.enqueue(a.dequeue());
|
||||
}
|
||||
return a.dequeue();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return a.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return a.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return a.toString();
|
||||
}
|
||||
}
|
||||
84
com/xgiovio/esercizi/SQueue.java
Normal file
84
com/xgiovio/esercizi/SQueue.java
Normal file
@@ -0,0 +1,84 @@
|
||||
package com.xgiovio.esercizi;
|
||||
|
||||
import exceptions.EmptyQueueException;
|
||||
import queue.Queue;
|
||||
import stack.ArrayStack;
|
||||
|
||||
/**
|
||||
* Created with MONSTER.
|
||||
* User: xgiovio
|
||||
* Date: 13/04/2014
|
||||
* Time: 23:01
|
||||
*/
|
||||
|
||||
// queue emulated via 2 stacks
|
||||
|
||||
public class SQueue<E> implements Queue<E> {
|
||||
|
||||
|
||||
private ArrayStack<E> accoda = new ArrayStack<E>();
|
||||
private ArrayStack<E> decoda = new ArrayStack<E>();
|
||||
|
||||
@Override
|
||||
public void enqueue(E element) {
|
||||
|
||||
accoda.push(element);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public E dequeue() throws EmptyQueueException {
|
||||
|
||||
if (accoda.isEmpty()){
|
||||
throw new EmptyQueueException();
|
||||
} else {
|
||||
|
||||
E temp;
|
||||
int size = accoda.size();
|
||||
for (int i = 0; i <size; i++) {
|
||||
decoda.push(accoda.pop());
|
||||
}
|
||||
temp = decoda.pop();
|
||||
size = decoda.size();
|
||||
for (int i = 0; i < size; i++) {
|
||||
accoda.push(decoda.pop());
|
||||
}
|
||||
return temp;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public E front() throws EmptyQueueException {
|
||||
if (accoda.isEmpty()){
|
||||
throw new EmptyQueueException();
|
||||
} else {
|
||||
|
||||
E temp;
|
||||
int size = accoda.size();
|
||||
for (int i = 0; i <size; i++) {
|
||||
decoda.push(accoda.pop());
|
||||
}
|
||||
temp = decoda.top();
|
||||
size = decoda.size();
|
||||
for (int i = 0; i < size; i++) {
|
||||
accoda.push(decoda.pop());
|
||||
}
|
||||
return temp;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return accoda.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return accoda.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return accoda.toString();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.xgiovio;
|
||||
package com.xgiovio.esercizi;
|
||||
|
||||
import exceptions.EmptyStackException;
|
||||
import stack.NodeStack;
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.xgiovio;
|
||||
package com.xgiovio.esercizi;
|
||||
|
||||
import stack.NodeStack;
|
||||
|
||||
69
com/xgiovio/esercizi/start_static_methods.java
Normal file
69
com/xgiovio/esercizi/start_static_methods.java
Normal file
@@ -0,0 +1,69 @@
|
||||
package com.xgiovio.esercizi;
|
||||
|
||||
/**
|
||||
* Created with MONSTER.
|
||||
* User: xgiovio
|
||||
* Date: 13/04/2014
|
||||
* Time: 22:18
|
||||
*/
|
||||
public class start_static_methods {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
System.out.println(static_methods.inverti("ehila"));
|
||||
|
||||
System.out.println(static_methods.checkParentheses("[()()()]([])"));
|
||||
|
||||
System.out.println (static_methods.isPalindrome("a"));
|
||||
|
||||
|
||||
///////////// test squeue
|
||||
SQueue<Integer> a = new SQueue<Integer>();
|
||||
a.enqueue(5);
|
||||
a.enqueue(10);
|
||||
a.enqueue(20);
|
||||
a.enqueue(30);
|
||||
a.enqueue(40);
|
||||
System.out.println (a);
|
||||
System.out.println (a.front());
|
||||
System.out.println (a.dequeue());
|
||||
System.out.println (a);
|
||||
a.enqueue(60);
|
||||
System.out.println (a);
|
||||
System.out.println (a.front());
|
||||
|
||||
System.out.println (static_methods.extract(a,0));
|
||||
///////////// end test squeue
|
||||
|
||||
|
||||
|
||||
QStack<Integer> b = new QStack<Integer>();
|
||||
b.push(1);
|
||||
b.push(2);
|
||||
b.push(3);
|
||||
b.push(4);
|
||||
|
||||
System.out.println (b);
|
||||
System.out.println (b.top());
|
||||
System.out.println (b.top());
|
||||
System.out.println (b.pop());
|
||||
System.out.println (b);
|
||||
System.out.println (b.top());
|
||||
|
||||
System.out.println (a);
|
||||
System.out.println (static_methods.isContained(a,115));
|
||||
System.out.println (a);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
419
com/xgiovio/esercizi/static_methods.java
Normal file
419
com/xgiovio/esercizi/static_methods.java
Normal 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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
210
com/xgiovio/test_2_prova_intercorso/ExBinaryTree_11_2_13.java
Normal file
210
com/xgiovio/test_2_prova_intercorso/ExBinaryTree_11_2_13.java
Normal file
@@ -0,0 +1,210 @@
|
||||
package com.xgiovio.test_2_prova_intercorso;
|
||||
|
||||
|
||||
/*
|
||||
|
||||
|
||||
|
||||
|
||||
L'albero T usato per il II test e` il seguente:
|
||||
|
||||
|
||||
4
|
||||
|
||||
/ \
|
||||
2 8
|
||||
/ \ / \
|
||||
1 3 4 10
|
||||
\ / \
|
||||
7 2 11
|
||||
|
||||
|
||||
L'albero T usato per il III test e` il seguente:
|
||||
|
||||
|
||||
4
|
||||
|
||||
/ \
|
||||
2 8
|
||||
/ \ / \
|
||||
1 3 4 10
|
||||
\ \ / \
|
||||
2 7 2 11
|
||||
|
||||
|
||||
L'albero T usato per il IV test e` il seguente:
|
||||
|
||||
|
||||
4
|
||||
|
||||
/ \
|
||||
2 8
|
||||
/ \ / \
|
||||
1 3 4 10
|
||||
\ / \ / \
|
||||
8 5 7 2 11
|
||||
/ \
|
||||
1 40
|
||||
|
||||
|
||||
|
||||
|
||||
Il programma deve stampare:
|
||||
|
||||
I test: Albero vuoto
|
||||
|
||||
II test: L'albero soddisfa la proprieta`.
|
||||
|
||||
III test: L'albero NON soddisfa la proprieta`.
|
||||
|
||||
IV test: L'albero NON soddisfa la proprieta`.
|
||||
|
||||
*/
|
||||
|
||||
import exceptions.EmptyTreeException;
|
||||
import exceptions.InvalidPositionException;
|
||||
import position.Position;
|
||||
import tree.binarytree.BTNode;
|
||||
import tree.binarytree.BTPosition;
|
||||
import tree.binarytree.BinaryTree;
|
||||
import tree.binarytree.LinkedBinaryTree;
|
||||
|
||||
public class ExBinaryTree_11_2_13 {
|
||||
|
||||
public static void main(String[] args){
|
||||
ExamBinaryTree <Integer>T= new ExamBinaryTree<Integer>();
|
||||
|
||||
System.out.print("I test: ");
|
||||
|
||||
try{check(T);}
|
||||
catch(EmptyTreeException e)
|
||||
{System.out.println("Albero vuoto");}
|
||||
|
||||
T.examAddRoot(4);
|
||||
T.examExpandExternal(T.root(), 2, 8 );
|
||||
T.examExpandExternal(T.left(T.root()), 1 , 3 );
|
||||
T.examExpandExternal(T.right(T.root()), 4 , 10 );
|
||||
T.examInsertRight(T.left(T.right(T.root())), 7 );
|
||||
T.examExpandExternal(T.right(T.right(T.root())), 2 , 11 );
|
||||
|
||||
System.out.print( "\nII test: ");
|
||||
if(check(T)) System.out.println("L'albero soddisfa la proprieta`.");
|
||||
else System.out.println("L'albero NON soddisfa la proprieta`.");
|
||||
|
||||
T.examInsertRight(T.right(T.left(T.root())), 2);
|
||||
System.out.print( "\nIII test: ");
|
||||
if(check(T)) System.out.println("L'albero soddisfa la proprieta`.");
|
||||
else System.out.println("L'albero NON soddisfa la proprieta`.");
|
||||
|
||||
T.replace(T.right(T.right(T.left(T.root()))), 8);
|
||||
T.examInsertLeft(T.left(T.right(T.root())),5);
|
||||
T.examExpandExternal(T.left(T.left(T.right(T.root()))), 1, 40);
|
||||
|
||||
System.out.print( "\nIV test: ");
|
||||
if(check(T)) System.out.println("L'albero soddisfa la proprieta`.");
|
||||
else System.out.println("L'albero NON soddisfa la proprieta`.");
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static boolean exec_check(BinaryTree<Integer> T, Position<Integer> start) {
|
||||
if (T.isExternal(start))
|
||||
return true;
|
||||
else {
|
||||
|
||||
if (T.hasLeft(start) && T.hasRight(start)){
|
||||
Integer leftv = T.left(start).element();
|
||||
Integer rightv = T.right(start).element();
|
||||
Integer myvalue = start.element();
|
||||
if (leftv < myvalue && rightv > myvalue)
|
||||
return (true && exec_check (T,T.left(start)) && exec_check (T,T.right(start)) ) ;
|
||||
return false;
|
||||
} else {
|
||||
if (T.hasLeft(start) && !T.hasRight(start)) {
|
||||
Integer leftv = T.left(start).element();
|
||||
Integer myvalue = start.element();
|
||||
if (leftv < myvalue)
|
||||
return (true && exec_check(T, T.left(start)));
|
||||
return false;
|
||||
} else {
|
||||
Integer rightv = T.right(start).element();
|
||||
Integer myvalue = start.element();
|
||||
if ( rightv > myvalue)
|
||||
return (true && exec_check (T,T.right(start)) ) ;
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//scrivere qui la funzione
|
||||
public static boolean check(BinaryTree<Integer> T){
|
||||
if (T.isEmpty())
|
||||
throw new EmptyTreeException();
|
||||
Position<Integer> start = T.root();
|
||||
return exec_check (T,start) ;
|
||||
|
||||
}
|
||||
|
||||
|
||||
//Sostituire size con in nome della variabile di istanza che tiene
|
||||
//traccia del numero di nodi nella vostra classe LinkedBinaryTree
|
||||
public static class ExamBinaryTree <E>extends LinkedBinaryTree<E> implements BinaryTree<E>{
|
||||
|
||||
|
||||
public Position<E> examAddRoot(E e){// throws NonEmptyTreeException {
|
||||
// if(!isEmpty())
|
||||
// throw new NonEmptyTreeException("L'albero ha gia una radice");
|
||||
size = 1;
|
||||
root = examCreateNode(e,null,null,null);
|
||||
return root;
|
||||
}
|
||||
|
||||
protected BTPosition<E> examCreateNode(E element, BTPosition<E> parent,
|
||||
BTPosition<E> left, BTPosition<E> right) {
|
||||
return new BTNode<E>(element,parent,left,right); }
|
||||
|
||||
public void examExpandExternal(Position<E> v, E l, E r)
|
||||
throws InvalidPositionException {
|
||||
if (!isExternal(v))
|
||||
throw new InvalidPositionException("Il nodo non e` una foglia");
|
||||
examInsertLeft(v, l);
|
||||
examInsertRight(v, r);
|
||||
}
|
||||
|
||||
|
||||
public Position<E> examInsertLeft(Position<E> v, E e)
|
||||
throws InvalidPositionException {
|
||||
BTPosition<E> vv = checkPosition(v);
|
||||
Position<E> leftPos = vv.getLeft();
|
||||
if (leftPos != null)
|
||||
throw new InvalidPositionException("il nodo ha gia` un figlio sin");
|
||||
BTPosition<E> ww = examCreateNode(e, vv, null, null);
|
||||
vv.setLeft(ww);
|
||||
size++;
|
||||
return ww;
|
||||
}
|
||||
public Position<E> examInsertRight(Position<E> v, E e)
|
||||
throws InvalidPositionException {
|
||||
BTPosition<E> vv = checkPosition(v);
|
||||
Position<E> rightPos = vv.getRight();
|
||||
if (rightPos != null)
|
||||
throw new InvalidPositionException("il nodo ha gia` un figlio destro");
|
||||
BTPosition<E> w = examCreateNode(e, vv, null, null);
|
||||
vv.setRight(w);
|
||||
size++;
|
||||
return w;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
164
com/xgiovio/test_2_prova_intercorso/ExGraph_15_6PerEserc.java
Normal file
164
com/xgiovio/test_2_prova_intercorso/ExGraph_15_6PerEserc.java
Normal file
@@ -0,0 +1,164 @@
|
||||
package com.xgiovio.test_2_prova_intercorso;
|
||||
|
||||
|
||||
/*Il programma deve stampare :
|
||||
|
||||
Test su un grafo che NON contiene cicli di lunghezza 3 passanti per il vertice 0:
|
||||
Il grafo contiene i vertici: 0 1 2 3 4 5 6 7 8
|
||||
e gli archi: (0,1)(0,2)(0,3)(1,4)(1,5)(1,6)(2,5)(2,6)(3,6)(4,6)(4,7)(4,8)(5,7)(5,8)(6,8)
|
||||
|
||||
Se invochiamo removeClosestVertices sul vertice 0 vengono cancellati i vertici:
|
||||
4 5 6 1 2 3
|
||||
|
||||
Test su un grafo che contiene cicli di lunghezza 3 passanti per il vertice 0:
|
||||
Il grafo contiene i vertici: 0 1 2 3 4 5 6 7 8
|
||||
e gli archi: (0,1)(0,2)(0,3)(0,4)(0,5)(1,4)(1,5)(1,6)(2,5)(2,6)(3,6)(4,6)(4,7)(4,8)(5,7)(5,8)(6,8)
|
||||
|
||||
Se invochiamo removeClosestVertices sul vertice 0 vengono cancellati i vertici:
|
||||
6 1 2 3 7 8 4 5
|
||||
|
||||
|
||||
*PS: ovviamente i vertici e gli archi potrebbero essere stampati in un diverso ordine
|
||||
*/
|
||||
|
||||
|
||||
import graph.AdjacencyListGraph;
|
||||
import graph.Edge;
|
||||
import graph.Graph;
|
||||
import graph.Vertex;
|
||||
import position.NodePositionList;
|
||||
import position.PositionList;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
public class ExGraph_15_6PerEserc {
|
||||
public static void main(String[] args){
|
||||
AdjacencyListGraph<Integer,String> G1= new AdjacencyListGraph<Integer,String>();
|
||||
AdjacencyListGraph<Integer,String> G2= new AdjacencyListGraph<Integer,String>();
|
||||
|
||||
//I test
|
||||
System.out.println("\n\nTest su un grafo che NON contiene cicli di lunghezza 3 passanti per il vertice 0:");
|
||||
System.out.print("Il grafo contiene i vertici: ");
|
||||
|
||||
Vertex<Integer>[] A= (Vertex<Integer>[]) new Vertex[9];
|
||||
for(int i=0;i<=8;i++)
|
||||
A[i]=G1.insertVertex(i);
|
||||
|
||||
for(int i= 1;i<4;i++)
|
||||
G1.insertEdge(A[0], A[i], null);
|
||||
|
||||
for(int i=1;i<=3;i++){
|
||||
for(int j= i+3;j<7;j++)
|
||||
G1.insertEdge(A[i], A[j], null);
|
||||
}
|
||||
for(int i=4;i<9;i++){
|
||||
for(int j= i+2;j<9;j++)
|
||||
G1.insertEdge(A[i], A[j], null);
|
||||
}
|
||||
|
||||
|
||||
Iterator<Vertex<Integer>> itV=G1.vertices().iterator();
|
||||
while(itV.hasNext())
|
||||
System.out.print(itV.next().element()+" ");
|
||||
|
||||
System.out.print("\ne gli archi: ");
|
||||
Iterator<Edge<String>> itE=G1.edges().iterator();
|
||||
while(itE.hasNext()){
|
||||
Edge <String> e= itE.next();
|
||||
System.out.print("("+G1.endVertices(e)[0].element()+","+G1.endVertices(e)[1].element()+")");
|
||||
}
|
||||
|
||||
|
||||
itV=removeClosestVertices(G1,A[0]).iterator();
|
||||
System.out.println("\n\nSe invochiamo removeClosestVertices sul vertice 0 vengono cancellati i vertici:");
|
||||
|
||||
while(itV.hasNext())
|
||||
System.out.print(itV.next()+" ");
|
||||
|
||||
|
||||
//II test
|
||||
System.out.println("\n\nTest su un grafo che contiene cicli di lunghezza 3 passanti per il vertice 0:");
|
||||
System.out.print("Il grafo contiene i vertici: ");
|
||||
|
||||
for(int i=0;i<=8;i++)
|
||||
A[i]=G2.insertVertex(i);
|
||||
|
||||
for(int i= 1;i<6;i++)
|
||||
G2.insertEdge(A[0], A[i], null);
|
||||
|
||||
for(int i=1;i<=3;i++){
|
||||
for(int j= i+3;j<7;j++)
|
||||
G2.insertEdge(A[i], A[j], null);
|
||||
}
|
||||
for(int i=4;i<8;i++){
|
||||
for(int j= i+2;j<9;j++)
|
||||
G2.insertEdge(A[i], A[j], null);
|
||||
}
|
||||
|
||||
itV=G2.vertices().iterator();
|
||||
while(itV.hasNext())
|
||||
System.out.print(itV.next().element()+" ");
|
||||
|
||||
System.out.print("\ne gli archi: ");
|
||||
itE=G2.edges().iterator();
|
||||
while(itE.hasNext()){
|
||||
Edge <String> e= itE.next();
|
||||
System.out.print("("+G2.endVertices(e)[0].element()+","+G2.endVertices(e)[1].element()+")");
|
||||
}
|
||||
|
||||
|
||||
itV=removeClosestVertices(G2,A[0]).iterator();
|
||||
System.out.println("\n\nSe invochiamo removeClosestVertices sul vertice 0 vengono cancellati i vertici:");
|
||||
|
||||
while(itV.hasNext())
|
||||
System.out.print(itV.next()+" ");
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
public static<V> boolean notpresentin (Vertex<V> v, PositionList<Vertex<V>> list ){
|
||||
|
||||
Iterator<Vertex<V>> it = list.iterator();
|
||||
for (;it.hasNext();){
|
||||
if (v.equals(it.next()))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
//scrivere qui la funzione
|
||||
public static<V,E> Iterable<Vertex<V>> removeClosestVertices(Graph<V,E> G,Vertex<V> v){
|
||||
NodePositionList<Vertex<V>> vertex_list = new NodePositionList<Vertex<V>>();
|
||||
|
||||
Iterator<Edge<E>> it = G.incidentEdges(v).iterator();
|
||||
for (;it.hasNext();){
|
||||
vertex_list.addLast(G.opposite( v, it.next() ) );
|
||||
}
|
||||
Iterator<Vertex<V>> it2 = vertex_list.iterator();
|
||||
for (;it2.hasNext();){
|
||||
Vertex<V> t = it2.next();
|
||||
Iterator<Edge<E>> it3 = G.incidentEdges(t).iterator();
|
||||
for (;it3.hasNext();){
|
||||
Edge<E> t2 = it3.next();
|
||||
Vertex<V> t3 = G.opposite( t, t2 );
|
||||
if (!t3.equals(v) && notpresentin (t3,vertex_list)){
|
||||
vertex_list.addFirst(t3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
Iterator<Vertex<V>> it4 = vertex_list.iterator();
|
||||
|
||||
Vertex<V> t = it4.next();
|
||||
G.removeVertex(t);
|
||||
|
||||
|
||||
return vertex_list;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
116
com/xgiovio/test_2_prova_intercorso/ExMap15_1.java
Normal file
116
com/xgiovio/test_2_prova_intercorso/ExMap15_1.java
Normal file
@@ -0,0 +1,116 @@
|
||||
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:
|
||||
M e` vuota
|
||||
D = < (50,29) (50,39) (50,49) (70,39) (70,49) (70,59) (70,69) (90,49) (90,59) (90,69) (90,79) (90,89) (10,9) (30,19) (30,29) >
|
||||
Dopo aver invocato addEntries su M e D, si ha M=< (90,49) (70,39) (50,29) (30,19) (10,9) >
|
||||
|
||||
II test:
|
||||
M=< (90,49) (70,39) (50,29) (30,19) (10,9) >
|
||||
D = < (50,29) (50,39) (50,49) (50,28) (70,39) (70,49) (70,59) (70,69) (70,38) (90,49) (90,59) (90,69) (90,79) (90,89) (90,48) (10,9) (10,8) (30,19) (30,29) (30,18) >.
|
||||
Nota che la mappa M contiene le entrate inserite dalla prima chiamata di addEntries
|
||||
e che al dizionario D sono state aggiunte le entrate (50,28) (30,18) (90,48) (10,8) (70,38).
|
||||
Dopo aver invocato addEntries su M e D, si ha M=< (90,49) (70,39) (50,29) (30,19) (10,9) >.
|
||||
|
||||
*/
|
||||
|
||||
|
||||
import dictionary.Dictionary;
|
||||
import dictionary.LinearProbingHashTable;
|
||||
import map.HashTableMap;
|
||||
import map.Map;
|
||||
import priorityqueue.Entry;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
|
||||
public class ExMap15_1 {
|
||||
public static void main(String[] args){
|
||||
Map<Integer,Integer> M = new HashTableMap<Integer,Integer>();
|
||||
Dictionary<Integer,Integer> D= new LinearProbingHashTable<Integer,Integer>();
|
||||
|
||||
|
||||
System.out.println("I test:");
|
||||
System.out.println("M e` vuota ");
|
||||
for(int i=10;i<100;i=i+20)
|
||||
for(int j=i/2+4;j<i;j=j+10)
|
||||
D.insert(i, j);
|
||||
Iterator<Entry<Integer,Integer>> itD= D.entries().iterator();
|
||||
System.out.print("D = < ");
|
||||
while(itD.hasNext())
|
||||
System.out.print(itD.next()+" ");
|
||||
System.out.println(">");
|
||||
|
||||
addEntries(M,D,new IntegerComparator());
|
||||
Iterator<Entry<Integer,Integer>> itM= M.entries().iterator();
|
||||
System.out.print("Dopo aver invocato addEntries su M e D, si ha M=< ");
|
||||
while(itM.hasNext())
|
||||
System.out.print(itM.next()+" ");
|
||||
System.out.println(">");
|
||||
|
||||
|
||||
System.out.println("\nII test: ");
|
||||
itM= M.entries().iterator();
|
||||
System.out.print("M=< ");
|
||||
while(itM.hasNext())
|
||||
System.out.print(itM.next()+" ");
|
||||
System.out.println(">");
|
||||
for(int i=10;i<100;i=i+20)
|
||||
D.insert(i, i/2+3);
|
||||
itD= D.entries().iterator();
|
||||
System.out.print("D = < ");
|
||||
while(itD.hasNext())
|
||||
System.out.print(itD.next()+" ");
|
||||
System.out.println(">.");
|
||||
System.out.println("Nota che la mappa M contiene le entrate inserite dalla prima chiamata di addEntries");
|
||||
System.out.println("e che al dizionario D sono state aggiunte le entrate (50,28) (30,18) (90,48) (10,8) (70,38).");
|
||||
addEntries(M,D,new IntegerComparator());
|
||||
itM= M.entries().iterator();
|
||||
System.out.print("Dopo aver invocato addEntries su M e D, si ha M=< ");
|
||||
while(itM.hasNext())
|
||||
System.out.print(itM.next()+" ");
|
||||
System.out.println(">.");
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
//scrivere qui la funzione
|
||||
public static <K> void addEntries(Map<K,K> M, Dictionary<K,K> D, Comparator<K> c){
|
||||
|
||||
Iterator<Entry<K,K>> it = D.entries().iterator();
|
||||
for (;it.hasNext();){
|
||||
Entry<K,K> e = it.next();
|
||||
K key = e.getKey();
|
||||
K value = null;
|
||||
if (M.get(key) == null ){
|
||||
Iterator<Entry<K,K>> it2 = D.findAll(key).iterator();
|
||||
int flag = 0;
|
||||
for (;it2.hasNext();){
|
||||
Entry<K,K>e2 = it2.next();
|
||||
if (flag == 0){
|
||||
flag = 1;
|
||||
value = e2.getValue();
|
||||
} else {
|
||||
if ( c.compare( e2.getValue(),value) < 0 ){
|
||||
value = e2.getValue();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
M.put(key,value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class IntegerComparator implements Comparator<Integer> {
|
||||
|
||||
public int compare(Integer a, Integer b) throws ClassCastException {
|
||||
return(a-b);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
152
com/xgiovio/test_2_prova_intercorso/ExPQ_21_2_11.java
Normal file
152
com/xgiovio/test_2_prova_intercorso/ExPQ_21_2_11.java
Normal file
@@ -0,0 +1,152 @@
|
||||
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):
|
||||
|
||||
I test
|
||||
Errore: almeno una delle code a priorita` e` vuota
|
||||
|
||||
II test
|
||||
La coda a priorita` Q1 contiene le entrate:
|
||||
(1,1) (3,3) (5,5) (7,7) (9,9) (11,11) (13,13)
|
||||
La coda a priorita` Q2 contiene le entrate:
|
||||
(1,1) (5,5) (9,9) (13,13) (17,17) (21,21) (25,25) (29,29)
|
||||
Dopo aver invocato subtract(Q1,Q2), la coda a priorita` Q1 contiene le entrate:
|
||||
(3,3) (7,7) (11,11)
|
||||
|
||||
III test
|
||||
La coda a priorita` Q1 contiene le entrate:
|
||||
(3,1) (5,1) (7,1) (7,2) (9,1) (9,2) (9,3) (11,1) (11,2) (11,3) (13,1) (13,2) (13,3) (13,4) (15,1) (15,2) (15,3) (15,4) (15,5) (25,54)
|
||||
La coda a priorita` Q2 contiene le entrate:
|
||||
(5,1) (9,1) (9,2) (13,1) (13,2) (13,3) (17,1) (17,2) (17,3) (17,4) (21,1) (21,2) (21,3) (21,4) (21,5) (25,1) (25,2) (25,3) (25,4) (25,5) (25,6)
|
||||
Dopo aver invocato subtract(Q1,Q2), la coda a priorita` Q1 contiene le entrate:
|
||||
(3,1) (7,2) (7,1) (11,1) (11,2) (11,3) (15,3) (15,5) (15,1) (15,2) (15,4)
|
||||
|
||||
|
||||
*/
|
||||
|
||||
import java.security.InvalidKeyException;
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
|
||||
|
||||
import position.NodePositionList;
|
||||
import priorityqueue.Entry;
|
||||
import priorityqueue.PriorityQueue;
|
||||
import priorityqueue.heap.HeapPriorityQueue;
|
||||
|
||||
public class ExPQ_21_2_11 {
|
||||
public static void main(String[] args) throws InvalidKeyException{
|
||||
PriorityQueue <Integer,Integer> Q1 = new HeapPriorityQueue<Integer,Integer>(new IntegerComparator());
|
||||
PriorityQueue <Integer,Integer> Q2 = new HeapPriorityQueue<Integer,Integer>(new IntegerComparator());
|
||||
Q2.insert(1, 5) ;
|
||||
|
||||
|
||||
System.out.println("I test");
|
||||
try{
|
||||
subtract(Q1,Q2, new IntegerComparator());
|
||||
}
|
||||
catch (EmptyPriorityQueueException err){
|
||||
System.out.println("Errore: almeno una delle code a priorita` e` vuota");
|
||||
}
|
||||
|
||||
System.out.println("\nII test");
|
||||
System.out.println("La coda a priorita` Q1 contiene le entrate:");
|
||||
for(int k=1;k<=14;k=k+2)
|
||||
{
|
||||
Q1.insert(k,k);
|
||||
System.out.print("("+k+","+k+") ");
|
||||
}
|
||||
|
||||
System.out.println("\nLa coda a priorita` Q2 contiene le entrate:");
|
||||
for(int k=1;k<=30;k=k+4)
|
||||
{
|
||||
Q2.insert(k,k);
|
||||
System.out.print("("+k+","+k+") ");
|
||||
}
|
||||
System.out.println("\nDopo aver invocato subtract(Q1,Q2), la coda a priorita` Q1 contiene le entrate:");
|
||||
subtract(Q1,Q2,new IntegerComparator());
|
||||
while(!Q1.isEmpty())
|
||||
System.out.print("("+Q1.min().getKey()+","+Q1.removeMin().getValue()+") ");
|
||||
|
||||
|
||||
Q1= new HeapPriorityQueue<Integer,Integer>(new IntegerComparator());
|
||||
Q2 = new HeapPriorityQueue<Integer,Integer>(new IntegerComparator());
|
||||
System.out.println("\n\nIII test");
|
||||
System.out.println("La coda a priorita` Q1 contiene le entrate:");
|
||||
for(int k=1;k<=15;k=k+2)
|
||||
for(int v=1;v<=k/3;v++){
|
||||
Q1.insert(k,v);
|
||||
System.out.print("("+k+","+v+") ");
|
||||
}
|
||||
Q1.insert(25,54);
|
||||
System.out.print("(25,54) ");
|
||||
System.out.println("\nLa coda a priorita` Q2 contiene le entrate:");
|
||||
for(int k=1;k<=25;k=k+4)
|
||||
for(int v=1;v<=k/4;v++){
|
||||
Q2.insert(k,v);
|
||||
System.out.print("("+k+","+v+") ");
|
||||
}
|
||||
|
||||
System.out.println("\nDopo aver invocato subtract(Q1,Q2), la coda a priorita` Q1 contiene le entrate:");
|
||||
subtract(Q1,Q2,new IntegerComparator());
|
||||
while(!Q1.isEmpty())
|
||||
System.out.print("("+Q1.min().getKey()+","+Q1.removeMin().getValue()+") ");
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static class IntegerComparator implements Comparator<Integer> {
|
||||
|
||||
public int compare(Integer a, Integer b) throws ClassCastException {
|
||||
return(a-b);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public static <K,V>void subtract (PriorityQueue<K,V> Q1, PriorityQueue <K,V> Q2,Comparator<K>c ) throws InvalidKeyException{
|
||||
|
||||
if( Q1.isEmpty() || Q2.isEmpty() )
|
||||
throw new EmptyPriorityQueueException();
|
||||
|
||||
Entry<K,V> a = Q1.removeMin();
|
||||
Entry<K,V> b = Q2.removeMin();
|
||||
|
||||
NodePositionList<Entry<K,V>> t = new NodePositionList<Entry<K, V>>();
|
||||
|
||||
for(;;){
|
||||
|
||||
if (c.compare(a.getKey(),b.getKey()) < 0){
|
||||
t.addLast(a);
|
||||
if (!Q1.isEmpty()){
|
||||
a=Q1.removeMin();
|
||||
continue;
|
||||
}else break;
|
||||
}
|
||||
|
||||
if (c.compare(a.getKey(),b.getKey()) == 0){
|
||||
if (!Q1.isEmpty()){
|
||||
a=Q1.removeMin();
|
||||
continue;
|
||||
}else break;
|
||||
}
|
||||
|
||||
if (c.compare(a.getKey(),b.getKey()) > 0){
|
||||
if (!Q2.isEmpty()){
|
||||
b=Q2.removeMin();
|
||||
continue;
|
||||
}else break;
|
||||
}
|
||||
}
|
||||
|
||||
Iterator<Entry<K,V>> it = t.iterator();
|
||||
for (;it.hasNext();){
|
||||
Entry<K,V> e = it.next();
|
||||
Q1.insert(e.getKey(),e.getValue());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
186
com/xgiovio/test_2_prova_intercorso/ExTree_17_1_2013.java
Normal file
186
com/xgiovio/test_2_prova_intercorso/ExTree_17_1_2013.java
Normal file
@@ -0,0 +1,186 @@
|
||||
package com.xgiovio.test_2_prova_intercorso;
|
||||
|
||||
|
||||
import exceptions.EmptyTreeException;
|
||||
import position.NodePositionList;
|
||||
import position.Position;
|
||||
import position.PositionList;
|
||||
import tree.LinkedTree;
|
||||
import tree.Tree;
|
||||
import tree.TreeNode;
|
||||
import tree.TreePosition;
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
/*****
|
||||
* L'albero usato per il II test e`
|
||||
*
|
||||
* 9
|
||||
* / / \ \
|
||||
* 10 11 12 13
|
||||
* / | \ / / \ \
|
||||
* 2 3 4 8 7 6 10
|
||||
* | / | \
|
||||
* 10 11 10 9
|
||||
*
|
||||
*
|
||||
|
||||
Il programma deve stampare:
|
||||
|
||||
I test
|
||||
L'albero e` vuoto.
|
||||
|
||||
|
||||
II test: T e` l'albero disegnato all'inizio del file.
|
||||
|
||||
I primi 2 nodi contenenti 10 sono:
|
||||
il nodo avente come padre il nodo contenente 9 e come figli i nodi contenenti gli elementi 2, 3, 4,
|
||||
il nodo avente come padre il nodo contenente 4
|
||||
|
||||
I primi 3 nodi contenenti 10 sono:
|
||||
il nodo avente come padre il nodo contenente 9 e come figli i nodi contenenti gli elementi 2, 3, 4,
|
||||
il nodo avente come padre il nodo contenente 4
|
||||
il nodo avente come padre il nodo contenente 6
|
||||
|
||||
I primi 4 nodi contenenti 10 sono:
|
||||
il nodo avente come padre il nodo contenente 9 e come figli i nodi contenenti gli elementi 2, 3, 4,
|
||||
il nodo avente come padre il nodo contenente 4
|
||||
il nodo avente come padre il nodo contenente 6
|
||||
il nodo avente come padre il nodo contenente 13
|
||||
|
||||
I primi 5 nodi contenenti 10 sono:
|
||||
il nodo avente come padre il nodo contenente 9 e come figli i nodi contenenti gli elementi 2, 3, 4,
|
||||
il nodo avente come padre il nodo contenente 4
|
||||
il nodo avente come padre il nodo contenente 6
|
||||
il nodo avente come padre il nodo contenente 13
|
||||
*/
|
||||
|
||||
public class ExTree_17_1_2013 {
|
||||
|
||||
public static void main(String[]args){
|
||||
|
||||
ExamTree<Integer > T = new ExamTree<Integer>();
|
||||
|
||||
|
||||
|
||||
System.out.println("I test");
|
||||
try{
|
||||
select(T,5,4);
|
||||
}
|
||||
catch(EmptyTreeException e){
|
||||
System.out.println("L'albero e` vuoto.\n");
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
T.examAddRoot(9);
|
||||
for(int i=10;i<=13 ; i++)
|
||||
T.examAddChild(i, T.root());
|
||||
|
||||
Iterator<Position<Integer>> figliRadice= T.children(T.root()).iterator();
|
||||
Position <Integer> figlioRadice = figliRadice.next();
|
||||
Position<Integer> figlio=null;
|
||||
for(int j=1;j<=3;j++)
|
||||
figlio = T.examAddChild(+(1+j), figlioRadice);
|
||||
T.examAddChild(10, figlio);
|
||||
figliRadice.next();
|
||||
figliRadice.next();
|
||||
figlioRadice = figliRadice.next();
|
||||
Position<Integer> nipoteRadice=null;
|
||||
for(int j=1;j<=3;j++)
|
||||
nipoteRadice=T.examAddChild((9-j), figlioRadice);
|
||||
T.examAddChild(10, figlioRadice);
|
||||
for(int j=11;j>=9;j--)
|
||||
T.examAddChild( j, nipoteRadice);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
System.out.println("\nII test: T e` l'albero disegnato all'inizio del file.");
|
||||
|
||||
for(int k=2;k<6;k++){
|
||||
System.out.print("\nI primi "+ k +" nodi contenenti 10 sono: ");
|
||||
|
||||
for(Position<Integer> p: select(T,10,k)){
|
||||
if(T.isRoot(p))System.out.print("\nil nodo radice, ");
|
||||
else System.out.print("\nil nodo avente come padre il nodo contenente "+ T.parent(p).element());
|
||||
if(T.isInternal(p)){
|
||||
System.out.print(" e come figli i nodi contenenti gli elementi ");
|
||||
for(Position<Integer> child : T.children(p))
|
||||
System.out.print(child.element()+", ");
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static <E> void exec_select (Tree<E> T, Position<E> start, E x, int k, PositionList<Position<E>> l) {
|
||||
|
||||
if (start.element().equals(x) && l.size() < k)
|
||||
l.addLast(start);
|
||||
if (l.size() < k && !T.isExternal(start)){
|
||||
Iterator<Position<E>>it = T.children(start).iterator();
|
||||
for (;it.hasNext();){
|
||||
Position<E> t = it.next();
|
||||
exec_select(T,t,x,k,l);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
//scrivere qui la funzione
|
||||
public static <E> Iterable <Position<E>> select(Tree<E> T, E x, int k){
|
||||
if (T.isEmpty()) throw new EmptyTreeException();
|
||||
NodePositionList<Position<E>> to_return = new NodePositionList<Position<E>>();
|
||||
exec_select(T,T.root(),x ,k,to_return);
|
||||
return to_return;
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static class ExamTree<E> extends LinkedTree<E> implements Tree<E>{
|
||||
|
||||
public Position<E> examAddRoot(E e){// throws NonEmptyTreeException {
|
||||
// if(!isEmpty())
|
||||
// throw new NonEmptyTreeException("L'albero ha gia` una radice");
|
||||
size = 1;
|
||||
root = examCreateNode(e,null,null);
|
||||
return root;
|
||||
}
|
||||
|
||||
|
||||
//aggiunge a v un figlio che ha come elemento element
|
||||
public Position <E> examAddChild(E element,Position <E> v){
|
||||
size++;
|
||||
Position<E> newP= examCreateNode(element,(TreePosition<E>) v,null);
|
||||
if(isExternal(v)){
|
||||
PositionList<Position<E>> figli = new NodePositionList<Position<E>>();
|
||||
((TreePosition<E>) v).setChildren(figli);
|
||||
figli.addLast(newP);}
|
||||
else((PositionList<Position<E>>)children(v)).addLast(newP);
|
||||
return newP;
|
||||
}
|
||||
|
||||
protected TreePosition<E> examCreateNode(E element, TreePosition<E> parent,
|
||||
PositionList<Position<E>> children) {
|
||||
return new TreeNode<E>(element,parent,children);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
71
com/xgiovio/test_2_prova_intercorso/Other_Functions.java
Normal file
71
com/xgiovio/test_2_prova_intercorso/Other_Functions.java
Normal file
@@ -0,0 +1,71 @@
|
||||
package com.xgiovio.test_2_prova_intercorso;
|
||||
|
||||
import arraylist.ArrayIndexList;
|
||||
import arraylist.IndexList;
|
||||
import graph.Edge;
|
||||
import graph.Graph;
|
||||
import graph.Vertex;
|
||||
import partition.ListPartition;
|
||||
import partition.Partition;
|
||||
import position.NodePositionList;
|
||||
import position.PositionList;
|
||||
import set.Set;
|
||||
|
||||
/**
|
||||
* Created with MONSTER.
|
||||
* User: xgiovio
|
||||
* Date: 01/06/2014
|
||||
* Time: 17:32
|
||||
*/
|
||||
public class Other_Functions {
|
||||
|
||||
public static <V,E> Partition<Vertex<V>> findConnectedComponents(Graph<V,E> G) {
|
||||
|
||||
|
||||
Partition<Vertex<V>> p = new ListPartition<Vertex<V>>();
|
||||
|
||||
Object VISITED = new Object();
|
||||
Object UNVISITED = new Object();
|
||||
Object STATUS = new Object();
|
||||
|
||||
for (Vertex<V> v : G.vertices()) {
|
||||
v.put(STATUS, UNVISITED);
|
||||
}
|
||||
|
||||
for (Vertex<V> v : G.vertices()) {
|
||||
|
||||
if (v.get(STATUS).equals(UNVISITED)) {
|
||||
|
||||
IndexList<PositionList<Vertex<V>>> layers = new ArrayIndexList<PositionList<Vertex<V>>>();
|
||||
|
||||
layers.add(0, new NodePositionList<Vertex<V>>());
|
||||
layers.get(0).addLast(v);
|
||||
v.put(STATUS, VISITED);
|
||||
Set<Vertex<V>> s = p.makeSet(v);
|
||||
|
||||
int i = 0;
|
||||
while (!layers.get(i).isEmpty()) {
|
||||
layers.add(i + 1, new NodePositionList<Vertex<V>>());
|
||||
|
||||
for (Vertex<V> vertexInLayer : layers.get(i)) {
|
||||
for (Edge<E> e : G.incidentEdges(vertexInLayer)) {
|
||||
if (e.get(STATUS).equals(UNVISITED)) {
|
||||
e.put(STATUS, VISITED);
|
||||
Vertex<V> w = G.opposite(vertexInLayer, e);
|
||||
if (w.get(STATUS).equals(UNVISITED)) {
|
||||
w.put(STATUS, VISITED);
|
||||
p.union(s, p.makeSet(w));
|
||||
layers.get(i + 1).addLast(w);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.xgiovio.test_prova_intercorso;
|
||||
|
||||
public class EmptyMyADT_Exception extends RuntimeException {
|
||||
|
||||
public EmptyMyADT_Exception(String error){super (error);}
|
||||
|
||||
}
|
||||
126
com/xgiovio/test_prova_intercorso/ExStack_17_4_13.java
Normal file
126
com/xgiovio/test_prova_intercorso/ExStack_17_4_13.java
Normal file
@@ -0,0 +1,126 @@
|
||||
package com.xgiovio.test_prova_intercorso;
|
||||
|
||||
import stack.ArrayStack;
|
||||
|
||||
//importare le classi necessarie
|
||||
|
||||
/* Il programma deve stampare:
|
||||
|
||||
I test
|
||||
Il carattere 'a' ha livello di annidamento 2
|
||||
Il carattere 'b' ha livello di annidamento 2
|
||||
Il carattere 'c' ha livello di annidamento 2
|
||||
Il carattere 'd' ha livello di annidamento 3
|
||||
Il carattere 'e' ha livello di annidamento 4
|
||||
Il carattere 'f' ha livello di annidamento 3
|
||||
Il carattere 'g' ha livello di annidamento 2
|
||||
Il carattere 'h' ha livello di annidamento 2
|
||||
Il carattere 'i' ha livello di annidamento 2
|
||||
Il carattere 'l' ha livello di annidamento 2
|
||||
Il carattere 'm' ha livello di annidamento 4
|
||||
Il carattere 'n' ha livello di annidamento 3
|
||||
Il carattere 'o' ha livello di annidamento 2
|
||||
Il carattere 'p' ha livello di annidamento 1
|
||||
Il carattere 'q' ha livello di annidamento 0
|
||||
|
||||
II test
|
||||
L'espressione non e` ben parentesizzata
|
||||
|
||||
III test
|
||||
L'espressione non e` ben parentesizzata
|
||||
|
||||
*/
|
||||
|
||||
public class ExStack_17_4_13 {
|
||||
|
||||
|
||||
|
||||
public static void main(String [] args){
|
||||
System.out.println("I test");
|
||||
String s="((abc(d(e)f)g)(hi)(l((m)n)o)p)q";
|
||||
for(int i=0;i<s.length();i++)
|
||||
for(int j=0;j<5;j++){
|
||||
char c= s.charAt(i);
|
||||
if(c!='(' && c!=')'&& checkLevel(s,s.charAt(i),j))
|
||||
System.out.println("Il carattere '" + s.charAt(i) + "' ha livello di annidamento "+ j);
|
||||
}
|
||||
|
||||
System.out.println("\nII test");
|
||||
s="((abc(d(e)f)g)(hi))(l((m)n)o)p)q";
|
||||
boolean f= false;
|
||||
for(int i=0;i<s.length();i++)
|
||||
for(int j=0;j<5;j++){
|
||||
char c= s.charAt(i);
|
||||
if(c!='(' && c!=')'&& checkLevel(s,s.charAt(i),j))
|
||||
{System.out.println("Il carattere '" + s.charAt(i) + "' ha livello di annidamento "+ j);
|
||||
f= true;
|
||||
}
|
||||
}
|
||||
if(f==false)System.out.println("L'espressione non e` ben parentesizzata");
|
||||
|
||||
|
||||
System.out.println("\nIII test");
|
||||
s="((abcd(e)(f)(g)(hi)(l((m)(n)o)p)q";
|
||||
f=false;
|
||||
for(int i=0;i<s.length();i++)
|
||||
for(int j=0;j<6;j++){
|
||||
char c= s.charAt(i);
|
||||
if(c!='(' && c!=')'&& checkLevel(s,s.charAt(i),j))
|
||||
{System.out.println("Il carattere '" + s.charAt(i) + "' ha livello di annidamento "+ j);
|
||||
f= true;
|
||||
}
|
||||
}
|
||||
if(f==false)System.out.println("L'espressione non e` ben parentesizzata");
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
//scrivere qui la funzione
|
||||
public static boolean checkLevel(String s, char x, int i){
|
||||
|
||||
ArrayStack<Character> data = new ArrayStack<Character>();
|
||||
int annidamento = 0;
|
||||
int found = 0;
|
||||
for (int n = 0 ; n< s.length() ;n++){
|
||||
if (s.charAt(n) == '('){
|
||||
data.push(s.charAt(n));
|
||||
annidamento++;
|
||||
if (annidamento > i){
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (s.charAt(n) == ')'){
|
||||
if (annidamento <= 0){
|
||||
return false;
|
||||
}else {
|
||||
for (int k = 0; k< data.size();k++){
|
||||
data.pop();
|
||||
}
|
||||
annidamento--;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (s.charAt(n) == x && annidamento == i && found == 0){
|
||||
found = 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (data.size() == 0 && found == 1){
|
||||
return true;
|
||||
}else {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
27
com/xgiovio/test_prova_intercorso/MyADT.java
Normal file
27
com/xgiovio/test_prova_intercorso/MyADT.java
Normal file
@@ -0,0 +1,27 @@
|
||||
package com.xgiovio.test_prova_intercorso;
|
||||
|
||||
public interface MyADT<E>{
|
||||
|
||||
|
||||
|
||||
public int size();
|
||||
|
||||
public boolean isEmpty();
|
||||
|
||||
/* se il numero di elementi contenuti nella struttura dati e` dispari,
|
||||
il metodo mid restituisce l<>elemento centrale; se il numero di elementi
|
||||
e` pari, il metodo restituisce null.
|
||||
*/
|
||||
public E mid() throws EmptyMyADT_Exception;
|
||||
|
||||
|
||||
|
||||
public E removeMid()throws EmptyMyADT_Exception;
|
||||
|
||||
/*
|
||||
Il metodo insert inserisce l<>elemento e alla fine della collezione
|
||||
*/
|
||||
public void insert(E e);
|
||||
|
||||
|
||||
}
|
||||
87
com/xgiovio/test_prova_intercorso/QueueMyADT.java
Normal file
87
com/xgiovio/test_prova_intercorso/QueueMyADT.java
Normal file
@@ -0,0 +1,87 @@
|
||||
package com.xgiovio.test_prova_intercorso;
|
||||
|
||||
import queue.NodeQueue;
|
||||
|
||||
public class QueueMyADT<E> implements MyADT<E> {
|
||||
|
||||
|
||||
public QueueMyADT(){
|
||||
data = new NodeQueue <E> ();
|
||||
}
|
||||
|
||||
NodeQueue <E> data;
|
||||
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
|
||||
return data.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
|
||||
return data.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public E mid() throws EmptyMyADT_Exception {
|
||||
|
||||
|
||||
if (data.size() < 1){
|
||||
throw new EmptyMyADT_Exception("Lista vuota");
|
||||
}
|
||||
|
||||
if (data.size() % 2 == 1){
|
||||
|
||||
E to_return = null;
|
||||
for (int i = 0 ; i< data.size() ;i++){
|
||||
if (i == data.size() / 2){
|
||||
to_return = data.front();
|
||||
}
|
||||
data.enqueue(data.dequeue());
|
||||
}
|
||||
return to_return;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public E removeMid() throws EmptyMyADT_Exception {
|
||||
|
||||
if (data.size() < 1){
|
||||
throw new EmptyMyADT_Exception("Lista vuota");
|
||||
}
|
||||
|
||||
if (data.size() % 2 == 1){
|
||||
|
||||
E to_return = null;
|
||||
int original_size = data.size();
|
||||
for (int i = 0 ; i< original_size ;i++){
|
||||
if (i == original_size / 2){
|
||||
to_return = data.dequeue();
|
||||
}else{
|
||||
data.enqueue(data.dequeue());
|
||||
}
|
||||
}
|
||||
return to_return;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void insert(E e) {
|
||||
data.enqueue(e);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return data.toString();
|
||||
}
|
||||
}
|
||||
30
com/xgiovio/test_prova_intercorso/test.java
Normal file
30
com/xgiovio/test_prova_intercorso/test.java
Normal file
@@ -0,0 +1,30 @@
|
||||
package com.xgiovio.test_prova_intercorso;
|
||||
|
||||
public class test {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
System.out.print(ExStack_17_4_13.checkLevel("((aad)())", 'd', 2));
|
||||
|
||||
QueueMyADT<Integer> a = new QueueMyADT<Integer>();
|
||||
a.insert(10);
|
||||
a.insert(20);
|
||||
a.insert(30);
|
||||
a.insert(40);
|
||||
a.insert(50);
|
||||
|
||||
System.out.print (a);
|
||||
|
||||
|
||||
System.out.print (a.mid());
|
||||
|
||||
System.out.print (a);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user