task_type
stringclasses 4
values | code_task
stringclasses 15
values | start_line
int64 4
1.79k
| end_line
int64 4
1.8k
| before
stringlengths 79
76.1k
| between
stringlengths 17
806
| after
stringlengths 2
72.6k
| reason_categories_output
stringlengths 2
2.24k
| horizon_categories_output
stringlengths 83
3.99k
⌀ | reason_freq_analysis
stringclasses 150
values | horizon_freq_analysis
stringlengths 23
185
⌀ |
---|---|---|---|---|---|---|---|---|---|---|
completion_java | MTreeTester | 392 | 393 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {'] | [' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));'] | [' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 392}, {'reason_category': 'If Body', 'usage_line': 392}, {'reason_category': 'Loop Body', 'usage_line': 393}, {'reason_category': 'If Body', 'usage_line': 393}] | Variable 'myQ' used at line 392 is defined at line 388 and has a Short-Range dependency.
Global_Variable 'myData' used at line 392 is defined at line 355 and has a Long-Range dependency.
Variable 'i' used at line 392 is defined at line 389 and has a Short-Range dependency.
Function 'getKey' used at line 392 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 392 is defined at line 122 and has a Long-Range dependency.
Function 'getData' used at line 392 is defined at line 443 and has a Long-Range dependency.
Variable 'query' used at line 393 is defined at line 388 and has a Short-Range dependency.
Global_Variable 'myData' used at line 393 is defined at line 355 and has a Long-Range dependency.
Variable 'i' used at line 393 is defined at line 389 and has a Short-Range dependency.
Function 'getKey' used at line 393 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 393 is defined at line 122 and has a Long-Range dependency. | {'Loop Body': 2, 'If Body': 2} | {'Variable Short-Range': 4, 'Global_Variable Long-Range': 2, 'Function Long-Range': 5} |
completion_java | MTreeTester | 404 | 406 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {'] | [' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }'] | [' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 404}, {'reason_category': 'If Condition', 'usage_line': 404}, {'reason_category': 'Loop Body', 'usage_line': 405}, {'reason_category': 'If Body', 'usage_line': 405}, {'reason_category': 'Loop Body', 'usage_line': 406}, {'reason_category': 'If Body', 'usage_line': 406}] | Variable 'query' used at line 404 is defined at line 398 and has a Short-Range dependency.
Global_Variable 'myData' used at line 404 is defined at line 355 and has a Long-Range dependency.
Variable 'i' used at line 404 is defined at line 403 and has a Short-Range dependency.
Function 'getKey' used at line 404 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 404 is defined at line 122 and has a Long-Range dependency.
Variable 'returnVal' used at line 405 is defined at line 400 and has a Short-Range dependency.
Class 'DataWrapper' used at line 405 is defined at line 429 and has a Medium-Range dependency.
Global_Variable 'myData' used at line 405 is defined at line 355 and has a Long-Range dependency.
Variable 'i' used at line 405 is defined at line 403 and has a Short-Range dependency.
Function 'getKey' used at line 405 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 405 is defined at line 122 and has a Long-Range dependency.
Function 'getData' used at line 405 is defined at line 443 and has a Long-Range dependency. | {'Loop Body': 3, 'If Condition': 1, 'If Body': 2} | {'Variable Short-Range': 4, 'Global_Variable Long-Range': 2, 'Function Long-Range': 5, 'Class Medium-Range': 1} |
completion_java | MTreeTester | 468 | 468 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);'] | [' myData.add (refTwo.getBoundingSphere (), refTwo);'] | [' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'myData' used at line 468 is defined at line 466 and has a Short-Range dependency.
Variable 'refTwo' used at line 468 is defined at line 463 and has a Short-Range dependency. | {} | {'Global_Variable Short-Range': 1, 'Variable Short-Range': 1} |
completion_java | MTreeTester | 485 | 488 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);'] | [' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }'] | [' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Condition', 'usage_line': 485}, {'reason_category': 'Loop Body', 'usage_line': 485}, {'reason_category': 'Loop Body', 'usage_line': 486}, {'reason_category': 'If Body', 'usage_line': 486}, {'reason_category': 'Loop Body', 'usage_line': 487}, {'reason_category': 'If Body', 'usage_line': 487}, {'reason_category': 'Loop Body', 'usage_line': 488}, {'reason_category': 'If Body', 'usage_line': 488}] | Variable 'newDist' used at line 485 is defined at line 484 and has a Short-Range dependency.
Variable 'bestDist' used at line 485 is defined at line 480 and has a Short-Range dependency.
Variable 'newDist' used at line 486 is defined at line 484 and has a Short-Range dependency.
Variable 'bestDist' used at line 486 is defined at line 480 and has a Short-Range dependency.
Variable 'i' used at line 487 is defined at line 482 and has a Short-Range dependency.
Variable 'bestIndex' used at line 487 is defined at line 481 and has a Short-Range dependency. | {'If Condition': 1, 'Loop Body': 4, 'If Body': 3} | {'Variable Short-Range': 6} |
completion_java | MTreeTester | 496 | 496 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {'] | [' myData.add (newRef.getBoundingSphere (), newRef);'] | [' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 496}] | Global_Variable 'myData' used at line 496 is defined at line 454 and has a Long-Range dependency.
Variable 'newRef' used at line 496 is defined at line 492 and has a Short-Range dependency. | {'If Body': 1} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 1} |
completion_java | MTreeTester | 501 | 502 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {'] | [' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);'] | [' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 501}, {'reason_category': 'If Body', 'usage_line': 502}] | Class 'SphereABCD' used at line 501 is defined at line 261 and has a Long-Range dependency.
Global_Variable 'myData' used at line 501 is defined at line 454 and has a Long-Range dependency.
Class 'InternalMTreeNodeABCD' used at line 502 is defined at line 450 and has a Long-Range dependency.
Variable 'newOne' used at line 502 is defined at line 501 and has a Short-Range dependency. | {'If Body': 2} | {'Class Long-Range': 2, 'Global_Variable Long-Range': 1, 'Variable Short-Range': 1} |
completion_java | MTreeTester | 513 | 514 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());'] | [' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);'] | [' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 513}, {'reason_category': 'If Condition', 'usage_line': 513}, {'reason_category': 'Loop Body', 'usage_line': 514}, {'reason_category': 'If Body', 'usage_line': 514}] | Function 'SphereABCD.intersects' used at line 513 is defined at line 284 and has a Long-Range dependency.
Global_Variable 'myData' used at line 513 is defined at line 454 and has a Long-Range dependency.
Variable 'i' used at line 513 is defined at line 511 and has a Short-Range dependency.
Function 'getKey' used at line 513 is defined at line 439 and has a Long-Range dependency.
Global_Variable 'myData' used at line 514 is defined at line 454 and has a Long-Range dependency.
Variable 'i' used at line 514 is defined at line 511 and has a Short-Range dependency.
Function 'getData' used at line 514 is defined at line 443 and has a Long-Range dependency.
Function 'findKClosest' used at line 514 is defined at line 510 and has a Short-Range dependency.
Variable 'query' used at line 514 is defined at line 510 and has a Short-Range dependency.
Variable 'myQ' used at line 514 is defined at line 510 and has a Short-Range dependency. | {'Loop Body': 2, 'If Condition': 1, 'If Body': 1} | {'Function Long-Range': 3, 'Global_Variable Long-Range': 2, 'Variable Short-Range': 4, 'Function Short-Range': 1} |
completion_java | MTreeTester | 525 | 529 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val'] | [' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }'] | [' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 525}, {'reason_category': 'Loop Body', 'usage_line': 526}, {'reason_category': 'If Condition', 'usage_line': 526}, {'reason_category': 'Loop Body', 'usage_line': 527}, {'reason_category': 'If Body', 'usage_line': 527}, {'reason_category': 'Loop Body', 'usage_line': 528}, {'reason_category': 'If Body', 'usage_line': 528}, {'reason_category': 'Loop Body', 'usage_line': 529}] | Variable 'i' used at line 525 is defined at line 525 and has a Short-Range dependency.
Global_Variable 'myData' used at line 525 is defined at line 454 and has a Long-Range dependency.
Variable 'query' used at line 526 is defined at line 520 and has a Short-Range dependency.
Global_Variable 'myData' used at line 526 is defined at line 454 and has a Long-Range dependency.
Variable 'i' used at line 526 is defined at line 525 and has a Short-Range dependency.
Function 'getKey' used at line 526 is defined at line 439 and has a Long-Range dependency.
Variable 'returnVal' used at line 527 is defined at line 522 and has a Short-Range dependency.
Global_Variable 'myData' used at line 527 is defined at line 454 and has a Long-Range dependency.
Variable 'i' used at line 527 is defined at line 525 and has a Short-Range dependency.
Function 'getData' used at line 527 is defined at line 443 and has a Long-Range dependency.
Function 'find' used at line 527 is defined at line 520 and has a Short-Range dependency.
Variable 'query' used at line 527 is defined at line 520 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 4, 'If Condition': 1, 'If Body': 2} | {'Variable Short-Range': 6, 'Global_Variable Long-Range': 3, 'Function Long-Range': 2, 'Function Short-Range': 1} |
completion_java | MTreeTester | 625 | 642 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;'] | [' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }'] | [' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 625}, {'reason_category': 'Loop Body', 'usage_line': 626}, {'reason_category': 'Define Stop Criteria', 'usage_line': 626}, {'reason_category': 'Loop Body', 'usage_line': 627}, {'reason_category': 'Loop Body', 'usage_line': 628}, {'reason_category': 'Loop Body', 'usage_line': 629}, {'reason_category': 'Loop Body', 'usage_line': 630}, {'reason_category': 'Loop Body', 'usage_line': 631}, {'reason_category': 'Loop Body', 'usage_line': 632}, {'reason_category': 'Loop Body', 'usage_line': 633}, {'reason_category': 'Loop Body', 'usage_line': 634}, {'reason_category': 'Loop Body', 'usage_line': 635}, {'reason_category': 'Loop Body', 'usage_line': 636}, {'reason_category': 'If Condition', 'usage_line': 636}, {'reason_category': 'Loop Body', 'usage_line': 637}, {'reason_category': 'If Body', 'usage_line': 637}, {'reason_category': 'Loop Body', 'usage_line': 638}, {'reason_category': 'If Body', 'usage_line': 638}, {'reason_category': 'Loop Body', 'usage_line': 639}, {'reason_category': 'If Body', 'usage_line': 639}, {'reason_category': 'Loop Body', 'usage_line': 640}, {'reason_category': 'If Body', 'usage_line': 640}, {'reason_category': 'Loop Body', 'usage_line': 641}, {'reason_category': 'Loop Body', 'usage_line': 642}] | Variable 'i' used at line 625 is defined at line 625 and has a Short-Range dependency.
Variable 'myData' used at line 625 is defined at line 622 and has a Short-Range dependency.
Variable 'i' used at line 626 is defined at line 625 and has a Short-Range dependency.
Variable 'j' used at line 626 is defined at line 626 and has a Short-Range dependency.
Variable 'myData' used at line 626 is defined at line 622 and has a Short-Range dependency.
Class 'DataWrapper' used at line 629 is defined at line 429 and has a Long-Range dependency.
Variable 'myData' used at line 629 is defined at line 622 and has a Short-Range dependency.
Variable 'i' used at line 629 is defined at line 625 and has a Short-Range dependency.
Class 'DataWrapper' used at line 630 is defined at line 429 and has a Long-Range dependency.
Variable 'myData' used at line 630 is defined at line 622 and has a Short-Range dependency.
Variable 'j' used at line 630 is defined at line 626 and has a Short-Range dependency.
Variable 'pointOne' used at line 633 is defined at line 629 and has a Short-Range dependency.
Function 'getPointInInterior' used at line 633 is defined at line 122 and has a Long-Range dependency.
Function 'getDistance' used at line 633 is defined at line 133 and has a Long-Range dependency.
Variable 'pointTwo' used at line 633 is defined at line 630 and has a Short-Range dependency.
Variable 'curDist' used at line 636 is defined at line 633 and has a Short-Range dependency.
Variable 'maxDist' used at line 636 is defined at line 624 and has a Medium-Range dependency.
Variable 'curDist' used at line 637 is defined at line 633 and has a Short-Range dependency.
Variable 'maxDist' used at line 637 is defined at line 624 and has a Medium-Range dependency.
Variable 'i' used at line 638 is defined at line 625 and has a Medium-Range dependency.
Variable 'bestI' used at line 638 is defined at line 623 and has a Medium-Range dependency.
Variable 'j' used at line 639 is defined at line 626 and has a Medium-Range dependency.
Variable 'bestJ' used at line 639 is defined at line 623 and has a Medium-Range dependency. | {'Define Stop Criteria': 2, 'Loop Body': 17, 'If Condition': 1, 'If Body': 4} | {'Variable Short-Range': 13, 'Class Long-Range': 2, 'Function Long-Range': 2, 'Variable Medium-Range': 6} |
completion_java | MTreeTester | 629 | 630 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys'] | [' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);'] | [' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 629}, {'reason_category': 'Loop Body', 'usage_line': 630}] | Class 'DataWrapper' used at line 629 is defined at line 429 and has a Long-Range dependency.
Variable 'myData' used at line 629 is defined at line 622 and has a Short-Range dependency.
Variable 'i' used at line 629 is defined at line 625 and has a Short-Range dependency.
Class 'DataWrapper' used at line 630 is defined at line 429 and has a Long-Range dependency.
Variable 'myData' used at line 630 is defined at line 622 and has a Short-Range dependency.
Variable 'j' used at line 630 is defined at line 626 and has a Short-Range dependency. | {'Loop Body': 2} | {'Class Long-Range': 2, 'Variable Short-Range': 4} |
completion_java | MTreeTester | 633 | 633 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them'] | [' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());'] | ['', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 633}] | Variable 'pointOne' used at line 633 is defined at line 629 and has a Short-Range dependency.
Function 'getPointInInterior' used at line 633 is defined at line 122 and has a Long-Range dependency.
Function 'getDistance' used at line 633 is defined at line 133 and has a Long-Range dependency.
Variable 'pointTwo' used at line 633 is defined at line 630 and has a Short-Range dependency. | {'Loop Body': 1} | {'Variable Short-Range': 2, 'Function Long-Range': 2} |
completion_java | MTreeTester | 636 | 640 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest'] | [' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }'] | [' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 636}, {'reason_category': 'If Condition', 'usage_line': 636}, {'reason_category': 'Loop Body', 'usage_line': 637}, {'reason_category': 'If Body', 'usage_line': 637}, {'reason_category': 'Loop Body', 'usage_line': 638}, {'reason_category': 'If Body', 'usage_line': 638}, {'reason_category': 'Loop Body', 'usage_line': 639}, {'reason_category': 'If Body', 'usage_line': 639}, {'reason_category': 'Loop Body', 'usage_line': 640}, {'reason_category': 'If Body', 'usage_line': 640}] | Variable 'curDist' used at line 636 is defined at line 633 and has a Short-Range dependency.
Variable 'maxDist' used at line 636 is defined at line 624 and has a Medium-Range dependency.
Variable 'curDist' used at line 637 is defined at line 633 and has a Short-Range dependency.
Variable 'maxDist' used at line 637 is defined at line 624 and has a Medium-Range dependency.
Variable 'i' used at line 638 is defined at line 625 and has a Medium-Range dependency.
Variable 'bestI' used at line 638 is defined at line 623 and has a Medium-Range dependency.
Variable 'j' used at line 639 is defined at line 626 and has a Medium-Range dependency.
Variable 'bestJ' used at line 639 is defined at line 623 and has a Medium-Range dependency. | {'Loop Body': 5, 'If Condition': 1, 'If Body': 4} | {'Variable Short-Range': 2, 'Variable Medium-Range': 6} |
completion_java | MTreeTester | 664 | 669 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects'] | [' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }'] | [' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 664}, {'reason_category': 'Loop Body', 'usage_line': 664}, {'reason_category': 'Loop Body', 'usage_line': 665}, {'reason_category': 'If Condition', 'usage_line': 665}, {'reason_category': 'Loop Body', 'usage_line': 666}, {'reason_category': 'If Body', 'usage_line': 666}, {'reason_category': 'Loop Body', 'usage_line': 667}, {'reason_category': 'If Body', 'usage_line': 667}, {'reason_category': 'Loop Body', 'usage_line': 668}, {'reason_category': 'If Body', 'usage_line': 668}, {'reason_category': 'Loop Body', 'usage_line': 669}] | Variable 'i' used at line 664 is defined at line 664 and has a Short-Range dependency.
Variable 'myData' used at line 664 is defined at line 622 and has a Long-Range dependency.
Variable 'myData' used at line 665 is defined at line 622 and has a Long-Range dependency.
Variable 'i' used at line 665 is defined at line 664 and has a Short-Range dependency.
Function 'getKey' used at line 665 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 665 is defined at line 122 and has a Long-Range dependency.
Function 'getDistance' used at line 665 is defined at line 133 and has a Long-Range dependency.
Variable 'pointOne' used at line 665 is defined at line 645 and has a Medium-Range dependency.
Variable 'bestDist' used at line 665 is defined at line 661 and has a Short-Range dependency.
Variable 'myData' used at line 666 is defined at line 622 and has a Long-Range dependency.
Variable 'i' used at line 666 is defined at line 664 and has a Short-Range dependency.
Function 'getKey' used at line 666 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 666 is defined at line 122 and has a Long-Range dependency.
Function 'getDistance' used at line 666 is defined at line 133 and has a Long-Range dependency.
Variable 'pointOne' used at line 666 is defined at line 645 and has a Medium-Range dependency.
Variable 'bestDist' used at line 666 is defined at line 661 and has a Short-Range dependency.
Variable 'i' used at line 667 is defined at line 664 and has a Short-Range dependency.
Variable 'bestIndex' used at line 667 is defined at line 660 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 6, 'If Condition': 1, 'If Body': 3} | {'Variable Short-Range': 7, 'Variable Long-Range': 3, 'Function Long-Range': 6, 'Variable Medium-Range': 2} |
completion_java | MTreeTester | 672 | 672 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in'] | [' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());'] | [' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 672}] | Variable 'listOne' used at line 672 is defined at line 649 and has a Medium-Range dependency.
Variable 'myData' used at line 672 is defined at line 622 and has a Long-Range dependency.
Variable 'bestIndex' used at line 672 is defined at line 660 and has a Medium-Range dependency.
Function 'getKey' used at line 672 is defined at line 439 and has a Long-Range dependency.
Function 'getData' used at line 672 is defined at line 443 and has a Long-Range dependency. | {'Loop Body': 1} | {'Variable Medium-Range': 2, 'Variable Long-Range': 1, 'Function Long-Range': 2} |
completion_java | MTreeTester | 676 | 676 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data'] | [' if (myData.size () == 0)'] | [' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Condition', 'usage_line': 676}, {'reason_category': 'Loop Body', 'usage_line': 676}] | Variable 'myData' used at line 676 is defined at line 622 and has a Long-Range dependency. | {'If Condition': 1, 'Loop Body': 1} | {'Variable Long-Range': 1} |
completion_java | MTreeTester | 681 | 686 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;'] | [' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }'] | [' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 681}, {'reason_category': 'Loop Body', 'usage_line': 681}, {'reason_category': 'Loop Body', 'usage_line': 682}, {'reason_category': 'If Condition', 'usage_line': 682}, {'reason_category': 'Loop Body', 'usage_line': 683}, {'reason_category': 'If Body', 'usage_line': 683}, {'reason_category': 'Loop Body', 'usage_line': 684}, {'reason_category': 'If Body', 'usage_line': 684}, {'reason_category': 'Loop Body', 'usage_line': 685}, {'reason_category': 'If Body', 'usage_line': 685}, {'reason_category': 'Loop Body', 'usage_line': 686}] | Variable 'i' used at line 681 is defined at line 681 and has a Short-Range dependency.
Variable 'myData' used at line 681 is defined at line 622 and has a Long-Range dependency.
Variable 'myData' used at line 682 is defined at line 622 and has a Long-Range dependency.
Variable 'i' used at line 682 is defined at line 681 and has a Short-Range dependency.
Function 'getKey' used at line 682 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 682 is defined at line 122 and has a Long-Range dependency.
Function 'getDistance' used at line 682 is defined at line 133 and has a Long-Range dependency.
Variable 'pointTwo' used at line 682 is defined at line 646 and has a Long-Range dependency.
Variable 'bestDist' used at line 682 is defined at line 680 and has a Short-Range dependency.
Variable 'myData' used at line 683 is defined at line 622 and has a Long-Range dependency.
Variable 'i' used at line 683 is defined at line 681 and has a Short-Range dependency.
Function 'getKey' used at line 683 is defined at line 439 and has a Long-Range dependency.
Function 'getPointInInterior' used at line 683 is defined at line 122 and has a Long-Range dependency.
Function 'getDistance' used at line 683 is defined at line 133 and has a Long-Range dependency.
Variable 'pointTwo' used at line 683 is defined at line 646 and has a Long-Range dependency.
Variable 'bestDist' used at line 683 is defined at line 680 and has a Short-Range dependency.
Variable 'i' used at line 684 is defined at line 681 and has a Short-Range dependency.
Variable 'bestIndex' used at line 684 is defined at line 660 and has a Medium-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 6, 'If Condition': 1, 'If Body': 3} | {'Variable Short-Range': 6, 'Variable Long-Range': 5, 'Function Long-Range': 6, 'Variable Medium-Range': 1} |
completion_java | MTreeTester | 689 | 689 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in'] | [' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());'] | [' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 689}] | Variable 'listTwo' used at line 689 is defined at line 650 and has a Long-Range dependency.
Variable 'myData' used at line 689 is defined at line 622 and has a Long-Range dependency.
Variable 'bestIndex' used at line 689 is defined at line 660 and has a Medium-Range dependency.
Function 'getKey' used at line 689 is defined at line 439 and has a Long-Range dependency.
Function 'getData' used at line 689 is defined at line 443 and has a Long-Range dependency. | {'Loop Body': 1} | {'Variable Long-Range': 2, 'Variable Medium-Range': 1, 'Function Long-Range': 2} |
completion_java | MTreeTester | 732 | 732 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);'] | [' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);'] | [' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Function 'LeafMTreeNodeABCD.setMaxSize' used at line 732 is defined at line 420 and has a Long-Range dependency.
Variable 'leafNodeSize' used at line 732 is defined at line 730 and has a Short-Range dependency. | {} | {'Function Long-Range': 1, 'Variable Short-Range': 1} |
completion_java | MTreeTester | 740 | 740 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point'] | [' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);'] | [' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'root' used at line 740 is defined at line 727 and has a Medium-Range dependency.
Variable 'keyToAdd' used at line 740 is defined at line 737 and has a Short-Range dependency.
Variable 'dataToAdd' used at line 740 is defined at line 737 and has a Short-Range dependency. | {} | {'Global_Variable Medium-Range': 1, 'Variable Short-Range': 2} |
completion_java | MTreeTester | 744 | 744 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {'] | [' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);'] | [' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Body', 'usage_line': 744}] | Class 'InternalMTreeNodeABCD' used at line 744 is defined at line 450 and has a Long-Range dependency.
Global_Variable 'root' used at line 744 is defined at line 727 and has a Medium-Range dependency.
Variable 'res' used at line 744 is defined at line 740 and has a Short-Range dependency. | {'If Body': 1} | {'Class Long-Range': 1, 'Global_Variable Medium-Range': 1, 'Variable Short-Range': 1} |
completion_java | MTreeTester | 750 | 750 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {'] | [' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); '] | [' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'root' used at line 750 is defined at line 727 and has a Medium-Range dependency.
Class 'SphereABCD' used at line 750 is defined at line 261 and has a Long-Range dependency.
Variable 'query' used at line 750 is defined at line 749 and has a Short-Range dependency.
Variable 'distance' used at line 750 is defined at line 749 and has a Short-Range dependency. | {} | {'Global_Variable Medium-Range': 1, 'Class Long-Range': 1, 'Variable Short-Range': 2} |
completion_java | MTreeTester | 756 | 757 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);'] | [' root.findKClosest (query, myQ);', ' return myQ.done ();'] | [' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'root' used at line 756 is defined at line 727 and has a Medium-Range dependency.
Variable 'query' used at line 756 is defined at line 754 and has a Short-Range dependency.
Variable 'myQ' used at line 756 is defined at line 755 and has a Short-Range dependency.
Function 'PQueueABCD.done' used at line 757 is defined at line 248 and has a Long-Range dependency. | {} | {'Global_Variable Medium-Range': 1, 'Variable Short-Range': 2, 'Function Long-Range': 1} |
completion_java | MTreeTester | 774 | 776 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {'] | [' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();'] | [' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Function 'InternalMTreeNodeABCD.setMaxSize' used at line 774 is defined at line 542 and has a Long-Range dependency.
Variable 'intNodeSize' used at line 774 is defined at line 773 and has a Short-Range dependency.
Function 'LeafMTreeNodeABCD.setMaxSize' used at line 775 is defined at line 420 and has a Long-Range dependency.
Variable 'leafNodeSize' used at line 775 is defined at line 773 and has a Short-Range dependency.
Class 'LeafMTreeNodeABCD' used at line 776 is defined at line 351 and has a Long-Range dependency.
Global_Variable 'root' used at line 776 is defined at line 770 and has a Short-Range dependency. | {} | {'Function Long-Range': 2, 'Variable Short-Range': 2, 'Class Long-Range': 1, 'Global_Variable Short-Range': 1} |
completion_java | MTreeTester | 786 | 788 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root'] | [' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }'] | [' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [{'reason_category': 'If Condition', 'usage_line': 786}, {'reason_category': 'If Body', 'usage_line': 787}, {'reason_category': 'If Body', 'usage_line': 788}] | Variable 'res' used at line 786 is defined at line 783 and has a Short-Range dependency.
Class 'InternalMTreeNodeABCD' used at line 787 is defined at line 450 and has a Long-Range dependency.
Global_Variable 'root' used at line 787 is defined at line 770 and has a Medium-Range dependency.
Variable 'res' used at line 787 is defined at line 783 and has a Short-Range dependency. | {'If Condition': 1, 'If Body': 2} | {'Variable Short-Range': 2, 'Class Long-Range': 1, 'Global_Variable Medium-Range': 1} |
completion_java | MTreeTester | 793 | 793 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {'] | [' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); '] | [' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Global_Variable 'root' used at line 793 is defined at line 770 and has a Medium-Range dependency.
Class 'SphereABCD' used at line 793 is defined at line 261 and has a Long-Range dependency.
Variable 'query' used at line 793 is defined at line 792 and has a Short-Range dependency.
Variable 'distance' used at line 793 is defined at line 792 and has a Short-Range dependency. | {} | {'Global_Variable Medium-Range': 1, 'Class Long-Range': 1, 'Variable Short-Range': 2} |
completion_java | MTreeTester | 798 | 801 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {'] | [' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }'] | [' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Class 'PQueueABCD' used at line 798 is defined at line 177 and has a Long-Range dependency.
Variable 'k' used at line 798 is defined at line 797 and has a Short-Range dependency.
Global_Variable 'root' used at line 799 is defined at line 770 and has a Medium-Range dependency.
Variable 'query' used at line 799 is defined at line 797 and has a Short-Range dependency.
Variable 'myQ' used at line 799 is defined at line 798 and has a Short-Range dependency.
Function 'PQueueABCD.done' used at line 800 is defined at line 248 and has a Long-Range dependency. | {} | {'Class Long-Range': 1, 'Variable Short-Range': 3, 'Global_Variable Medium-Range': 1, 'Function Long-Range': 1} |
completion_java | MTreeTester | 804 | 806 | ['import junit.framework.TestCase;', 'import java.util.ArrayList;', 'import java.util.Random;', 'import java.util.Collections;', '', '// this is a map from a set of keys of type PointInMetricSpace to a', '// set of data of type DataType', 'interface IMTree <Key extends IPointInMetricSpace <Key>, Data> {', ' ', ' // insert a new key/data pair into the map', ' void insert (Key keyToAdd, Data dataToAdd);', ' ', ' // find all of the key/data pairs in the map that fall within a', ' // particular distance of query point if no results are found, then', ' // an empty array is returned (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> find (Key query, double distance);', ' ', ' // find the k closest key/data pairs in the map to a particular', ' // query point ', ' //', ' // if the number of points in the map is less than k, then the', ' // returned list will have less than k pairs in it', ' //', ' // if the number of points is zero, then an empty array is returned', ' // (NOT a null!)', ' ArrayList <DataWrapper <Key, Data>> findKClosest (Key query, int k);', ' ', ' // returns the number of nodes that exist on a path from root to leaf in the tree...', ' // whtever the details of the implementation are, a tree with a single leaf node should return 1, and a tree', ' // with more than one lead node should return at least two (since it must have at least one internal node).', ' public int depth ();', ' ', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', '', 'interface IDoubleVector {', '', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '// this correponds to some geometric object in a metric space; the object is built out of', '// one or more points of type PointInMetricSpace', 'interface IObjectInMetricSpaceABCD <PointInMetricSpace extends IPointInMetricSpace<PointInMetricSpace>> {', ' ', ' // get the maximum distance from some point on the shape to a particular point in the metric space', ' double maxDistanceTo (PointInMetricSpace checkMe);', ' ', ' // return some arbitrary point on the interior of the geometric object', ' PointInMetricSpace getPointInInterior ();', '}', '', '', '// this interface corresponds to a point in some metric space', 'interface IPointInMetricSpace <PointInMetricSpace> {', ' ', ' // get the distance to another point', ' // ', ' // for this to work in an M-Tree, distances should be "metric" and', ' // obey the triangle inequality', ' double getDistance (PointInMetricSpace toMe);', '}', '', '// this is the basic node type in the structure', 'interface IMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> {', ' ', ' // insert a new key/data pair into the structure. The return value is a new MTreeNode if there was', ' // a split in response to the insertion, or a null if there was no split', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd);', ' ', ' // find all of the key/data pairs in the structure that fall within a particular query sphere', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query); ', ' ', ' // find the set of items closest to the given query point', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ);', ' ', ' // returns a sphere that totally encompasses everything in the node and its subtree', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', ' ', ' // returns the depth', ' public int depth ();', '}', '', '// this is a point in a particular metric space', 'class PointABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the point', ' private PointInMetricSpace me;', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return me; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return checkMe.getDistance (me); ', ' }', ' ', ' // contruct a point', ' public PointABCD (PointInMetricSpace useMe) {', ' me = useMe; ', ' }', '}', '', 'class PQueueABCD <PointInMetricSpace, DataType> {', ' ', ' // this is an object in the queue', ' private class Wrapper {', ' DataWrapper <PointInMetricSpace, DataType> myData;', ' double distance;', ' }', ' ', ' // this is the actual queue', ' ArrayList <Wrapper> myList;', ' ', ' // this is the largest distance value currently in the queue', ' double large;', ' ', ' // this is the max number of objects', ' int maxCount;', ' ', ' // create a priority queue with the speced number of slots', ' PQueueABCD (int maxCountIn) {', ' maxCount = maxCountIn;', ' myList = new ArrayList <Wrapper> ();', ' large = 9e99;', ' }', ' ', ' // get the largest distance in the queue', ' double getDist () {', ' return large;', ' }', ' ', ' // add a new object to the queue... the insertion is ignored if the distance value', ' // exceeds the largest that is in the queue and the queue is already full', ' void insert (PointInMetricSpace key, DataType data, double distance) {', ' ', ' // if we are full, remove the one with the largest distance', ' if (myList.size () == maxCount && distance < large) {', ' ', ' int badIndex = 0;', ' double maxDist = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > maxDist) {', ' maxDist = myList.get (i).distance;', ' badIndex = i;', ' }', ' }', ' ', ' myList.remove (badIndex);', ' }', ' ', ' // see if there is room', ' if (myList.size () < maxCount) {', ' ', ' // add it ', ' Wrapper newOne = new Wrapper ();', ' newOne.myData = new DataWrapper <PointInMetricSpace, DataType> (key, data);', ' newOne.distance = distance;', ' myList.add (newOne); ', ' }', ' ', ' // if we are full, reset the max distance', ' if (myList.size () == maxCount) {', ' large = 0.0;', ' for (int i = 0; i < myList.size (); i++) {', ' if (myList.get (i).distance > large) {', ' large = myList.get (i).distance;', ' }', ' }', ' }', ' ', ' }', ' ', ' // extracts the contents of the queue', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> done () {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' for (int i = 0; i < myList.size (); i++) {', ' returnVal.add (myList.get (i).myData); ', ' }', ' ', ' return returnVal;', ' }', ' ', '}', '', '// this is a sphere in a particular metric space', 'class SphereABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>> implements', ' IObjectInMetricSpaceABCD <PointInMetricSpace> {', '', ' // the center of the sphere and its radius', ' private PointInMetricSpace center;', ' private double radius;', ' ', ' // build a sphere out of its center and its radius', ' public SphereABCD (PointInMetricSpace centerIn, double radiusIn) {', ' center = centerIn;', ' radius = radiusIn;', ' }', ' ', ' // increase the size of the sphere so it contains the object swallowMe', ' public void swallow (IObjectInMetricSpaceABCD <PointInMetricSpace> swallowMe) {', ' ', ' // see if we need to increase the radius to swallow this guy', ' double dist = swallowMe.maxDistanceTo (center);', ' if (dist > radius)', ' radius = dist;', ' }', ' ', ' // check to see if a sphere intersects another sphere', ' public boolean intersects (SphereABCD <PointInMetricSpace> me) {', ' return (me.center.getDistance (center) <= me.radius + radius);', ' }', ' ', ' // check to see if the sphere contains a point', ' public boolean contains (PointInMetricSpace checkMe) {', ' return (checkMe.getDistance (center) <= radius);', ' }', ' ', ' public PointInMetricSpace getPointInInterior () {', ' return center; ', ' }', ' ', ' public double maxDistanceTo (PointInMetricSpace checkMe) {', ' return radius + checkMe.getDistance (center); ', ' }', '}', '', '', '', 'class OneDimPoint implements IPointInMetricSpace <OneDimPoint> {', ' ', ' // this is the actual double', ' Double value;', ' ', ' // construct this out of a double value', ' public OneDimPoint (double makeFromMe) {', ' value = new Double (makeFromMe);', ' }', ' ', ' // get the distance to another point', ' public double getDistance (OneDimPoint toMe) {', ' if (value > toMe.value)', ' return value - toMe.value;', ' else', ' return toMe.value - value;', ' }', ' ', '}', '', 'class MultiDimPoint implements IPointInMetricSpace <MultiDimPoint> {', ' ', ' // this is the point in a multidimensional space', ' IDoubleVector me;', ' ', ' // make this out of an IDoubleVector', ' public MultiDimPoint (IDoubleVector useMe) {', ' me = useMe;', ' }', ' ', ' // get the Euclidean distance to another point', ' public double getDistance (MultiDimPoint toMe) {', ' double distance = 0.0;', ' try {', ' for (int i = 0; i < me.getLength (); i++) {', ' double diff = me.getItem (i) - toMe.me.getItem (i);', ' diff *= diff;', ' distance += diff;', ' }', ' } catch (OutOfBoundsException e) {', ' throw new IndexOutOfBoundsException ("Can\'t compare two MultiDimPoint objects with different dimensionality!"); ', ' }', ' return Math.sqrt(distance);', ' }', ' ', '}', '// this is a leaf node', 'class LeafMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements ', ' IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myData;', ' ', ' // contructor that takes a data list and builds a node out of it', ' private LeafMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> myDataIn) {', ' myData = myDataIn; ', ' }', ' ', ' // constructor that creates an empty node', ' public LeafMTreeNodeABCD () {', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> (); ', ' }', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // just add in the new data', ' myData.add (new PointABCD <PointInMetricSpace> (keyToAdd), dataToAdd);', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, PointABCD <PointInMetricSpace>, DataType> newOne = myData.splitInTwo ();', ' LeafMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' myQ.insert (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData (), ', ' query.getDistance (myData.get (i).getKey ().getPointInInterior ()));', ' }', ' }', ' }', ' ', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.contains (myData.get (i).getKey ().getPointInInterior ())) {', ' returnVal.add (new DataWrapper <PointInMetricSpace, DataType> (myData.get (i).getKey ().getPointInInterior (), myData.get (i).getData ()));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return 1; ', ' }', '', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', '// this silly little class is just a wrapper for a key, data pair', 'class DataWrapper <Key, Data> {', ' ', ' Key key;', ' Data data;', ' ', ' public DataWrapper (Key keyIn, Data dataIn) {', ' key = keyIn;', ' data = dataIn;', ' }', ' ', ' public Key getKey () {', ' return key;', ' }', ' ', ' public Data getData () {', ' return data;', ' }', '}', '', '', '// this is an internal node', 'class InternalMTreeNodeABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType>', ' implements IMTreeNodeABCD <PointInMetricSpace, DataType> {', ' ', ' // this holds all of the data in the leaf node', ' private IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> myData;', ' ', ' // get the sphere that bounds this node', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myData.getBoundingSphere (); ', ' }', ' ', ' // this constructs a new internal node that holds precisely the two nodes that are passed in', ' public InternalMTreeNodeABCD (IMTreeNodeABCD <PointInMetricSpace, DataType> refOne,', ' IMTreeNodeABCD <PointInMetricSpace, DataType> refTwo) {', ' ', ' // create a necw list and add the two guys in', ' myData = new ChrisMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> ();', ' myData.add (refOne.getBoundingSphere (), refOne);', ' myData.add (refTwo.getBoundingSphere (), refTwo);', ' }', ' ', ' // this constructs a new node that holds the list of data that we were passed in', ' public InternalMTreeNodeABCD (IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> useMe) {', ' myData = useMe; ', ' }', ' ', ' // from the interface', ' public IMTreeNodeABCD <PointInMetricSpace, DataType> insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // find the best child; this is the one we are closest to', ' double bestDist = 9e99;', ' int bestIndex = 0;', ' for (int i = 0; i < myData.size (); i++) {', ' ', ' double newDist = myData.get (i).getKey ().getPointInInterior ().getDistance (keyToAdd);', ' if (newDist < bestDist) {', ' bestDist = newDist;', ' bestIndex = i;', ' }', ' }', ' ', ' // do the recursive insert', ' IMTreeNodeABCD <PointInMetricSpace, DataType> newRef = myData.get (bestIndex).getData ().insert (keyToAdd, dataToAdd);', ' ', ' // if we got something back, then there was a split, so add the new node into our list', ' if (newRef != null) {', ' myData.add (newRef.getBoundingSphere (), newRef);', ' }', ' ', ' // if we exceed the max size, then split and create a new node', ' if (myData.size () > getMaxSize ()) {', ' IMetricDataListABCD <PointInMetricSpace, SphereABCD <PointInMetricSpace>, IMTreeNodeABCD <PointInMetricSpace, DataType>> newOne = myData.splitInTwo ();', ' InternalMTreeNodeABCD <PointInMetricSpace, DataType> returnVal = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (newOne);', ' return returnVal;', ' }', ' ', ' // otherwise, we return a null to indcate that a split did not occur', ' return null;', ' }', ' ', ' public void findKClosest (PointInMetricSpace query, PQueueABCD <PointInMetricSpace, DataType> myQ) {', ' for (int i = 0; i < myData.size (); i++) {', ' SphereABCD <PointInMetricSpace> mySphere = new SphereABCD <PointInMetricSpace> (query, myQ.getDist ());', ' if (mySphere.intersects (myData.get (i).getKey ())) {', ' myData.get (i).getData ().findKClosest (query, myQ);', ' }', ' }', ' }', ' ', ' // from the interface', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (SphereABCD <PointInMetricSpace> query) {', ' ', ' ArrayList <DataWrapper <PointInMetricSpace, DataType>> returnVal = new ArrayList <DataWrapper <PointInMetricSpace, DataType>> ();', ' ', ' // just search thru every entry and look for a match... add every match into the return val', ' for (int i = 0; i < myData.size (); i++) {', ' if (query.intersects (myData.get (i).getKey ())) {', ' returnVal.addAll (myData.get (i).getData ().find (query));', ' }', ' }', ' ', ' return returnVal;', ' }', ' ', ' public int depth () {', ' return myData.get (0).getData ().depth () + 1; ', ' }', ' ', ' // this is the max number of entries in the node', ' private static int maxSize;', ' ', ' // and a getter and setter', ' public static void setMaxSize (int toMe) {', ' maxSize = toMe; ', ' }', ' public static int getMaxSize () {', ' return maxSize;', ' }', '}', '', 'abstract class AMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> implements IMetricDataListABCD <PointInMetricSpace,KeyType, DataType> {', '', ' // this is the data that is actually stored in the list', ' private ArrayList <DataWrapper <KeyType, DataType>> myData;', ' ', ' // this is the sphere that bounds everything in the list', ' private SphereABCD <PointInMetricSpace> myBoundingSphere;', ' ', ' public SphereABCD <PointInMetricSpace> getBoundingSphere () {', ' return myBoundingSphere; ', ' }', ' ', ' public int size () {', ' if (myData != null)', ' return myData.size (); ', ' else', ' return 0;', ' }', ' ', ' public DataWrapper <KeyType, DataType> get (int pos) {', ' return myData.get (pos);', ' }', ' ', ' public void replaceKey (int pos, KeyType keyToAdd) {', ' DataWrapper <KeyType, DataType> temp = myData.remove (pos);', ' DataWrapper <KeyType, DataType> newOne = new DataWrapper <KeyType, DataType> (keyToAdd, temp.getData ());', ' myData.add (pos, newOne);', ' }', ' ', ' public void add (KeyType keyToAdd, DataType dataToAdd) {', ' ', ' // if this is the first add, then set everyone up', ' if (myData == null) {', ' PointInMetricSpace myCentroid = keyToAdd.getPointInInterior ();', ' myBoundingSphere = new SphereABCD <PointInMetricSpace> (myCentroid, keyToAdd.maxDistanceTo (myCentroid));', ' myData = new ArrayList <DataWrapper <KeyType, DataType>> ();', ' ', ' // otherwise, extend the sphere if needed', ' } else {', ' myBoundingSphere.swallow (keyToAdd);', ' }', ' ', ' // add the data', ' myData.add (new DataWrapper <KeyType, DataType> (keyToAdd, dataToAdd));', ' }', ' ', ' // we want to potentially allow many implementations of the splitting lalgorithm', ' abstract public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // this is here so the actual splitting algorithn can access the list and change the sphere', ' protected ArrayList <DataWrapper <KeyType, DataType>> getList () {', ' return myData;', ' }', ' ', ' // this is here so the splitting algorithm can modify the list and the sphere', ' protected void replaceGuts (AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> withMe) {', ' myData = withMe.myData;', ' myBoundingSphere = withMe.myBoundingSphere;', ' }', ' ', '}', '', '// this is a particular implementation of the metric data list that uses a simple quadratic clustering', '// algorithm to perform a list split. It picks two "seeds" (the most distant objects) and then repeatedly', '// adds to the two new lists by choosing the objects closest to the seeds', 'class ChrisMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> extends AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> {', '', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo () {', ' ', ' // first, we need to find the two most distant points in the list', ' ArrayList <DataWrapper <KeyType, DataType>> myData = getList ();', ' int bestI = 0, bestJ = 0;', ' double maxDist = -1.0;', ' for (int i = 0; i < myData.size (); i++) {', ' for (int j = i + 1; j < myData.size (); j++) {', ' ', ' // get the two keys', ' DataWrapper <KeyType, DataType> pointOne = myData.get (i);', ' DataWrapper <KeyType, DataType> pointTwo = myData.get (j);', ' ', ' // find the difference between them', ' double curDist = pointOne.getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', '', ' // see if it is the biggest', ' if (curDist > maxDist) {', ' maxDist = curDist;', ' bestI = i;', ' bestJ = j;', ' }', ' }', ' }', ' ', ' // now, we have the best two points; those are seeds for the clustering', ' DataWrapper <KeyType, DataType> pointOne = myData.remove (bestI);', ' DataWrapper <KeyType, DataType> pointTwo = myData.remove (bestJ - 1);', ' ', ' // these are the two new lists', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listOne = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' AMetricDataListABCD <PointInMetricSpace, KeyType, DataType> listTwo = new ChrisMetricDataListABCD <PointInMetricSpace, KeyType, DataType> ();', ' ', ' // put the two seeds in', ' listOne.add (pointOne.getKey (), pointOne.getData ());', ' listTwo.add (pointTwo.getKey (), pointTwo.getData ());', ' ', ' // and add everyone else in', ' while (myData.size () != 0) {', ' ', ' // find the one closest to the first seed', ' int bestIndex = 0;', ' double bestDist = 9e99;', ' ', ' // loop thru all of the candidate data objects', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointOne.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listOne.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' ', ' // break if no more data', ' if (myData.size () == 0)', ' break;', ' ', ' // loop thru all of the candidate data objects', ' bestDist = 9e99;', ' for (int i = 0; i < myData.size (); i++) {', ' if (myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ()) < bestDist) {', ' bestDist = myData.get (i).getKey ().getPointInInterior ().getDistance (pointTwo.getKey ().getPointInInterior ());', ' bestIndex = i;', ' }', ' }', ' ', ' // and add the best in', ' listTwo.add (myData.get (bestIndex).getKey (), myData.get (bestIndex).getData ());', ' myData.remove (bestIndex);', ' }', ' ', ' // now we replace our own guts with the first list', ' replaceGuts (listOne);', ' ', ' // and return the other list', ' return listTwo;', ' }', '}', '', 'interface IMetricDataListABCD <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, ', ' KeyType extends IObjectInMetricSpaceABCD <PointInMetricSpace>, DataType> {', ' ', ' // add a new pair to the list', ' public void add (KeyType keyToAdd, DataType dataToAdd);', ' ', ' // replace a key at the indicated position', ' public void replaceKey (int pos, KeyType keyToAdd);', ' ', ' // get the key, data pair that resides at a particular position', ' public DataWrapper <KeyType, DataType> get (int pos);', ' ', ' // return the number of items in the list', ' public int size ();', ' ', ' // split the list in two, using some clutering algorithm', ' public IMetricDataListABCD <PointInMetricSpace, KeyType, DataType> splitInTwo ();', ' ', ' // get a sphere that totally bounds all of the objects in the list', ' public SphereABCD <PointInMetricSpace> getBoundingSphere ();', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class MTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public MTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth', ' public int depth () {', ' return root.depth (); ', ' }', '}', '', '// this implements a map from a set of keys of type PointInMetricSpace to a set of data of type DataType', 'class SCMTree <PointInMetricSpace extends IPointInMetricSpace <PointInMetricSpace>, DataType> implements IMTree <PointInMetricSpace, DataType> {', ' ', ' // this is the actual tree', ' private IMTreeNodeABCD <PointInMetricSpace, DataType> root;', ' ', ' // constructor... the two params set the number of entries in leaf and internal nodes', ' public SCMTree (int intNodeSize, int leafNodeSize) {', ' InternalMTreeNodeABCD.setMaxSize (intNodeSize);', ' LeafMTreeNodeABCD.setMaxSize (leafNodeSize);', ' root = new LeafMTreeNodeABCD <PointInMetricSpace, DataType> ();', ' }', ' ', ' // insert a new key/data pair into the map', ' public void insert (PointInMetricSpace keyToAdd, DataType dataToAdd) {', ' ', ' // insert the new data point', ' IMTreeNodeABCD <PointInMetricSpace, DataType> res = root.insert (keyToAdd, dataToAdd);', ' ', ' // if we got back a root split, then construct a new root', ' if (res != null) {', ' root = new InternalMTreeNodeABCD <PointInMetricSpace, DataType> (root, res);', ' }', ' }', ' ', ' // find all of the key/data pairs in the map that fall within a particular distance of query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> find (PointInMetricSpace query, double distance) {', ' return root.find (new SphereABCD <PointInMetricSpace> (query, distance)); ', ' }', ' ', ' // find the k closest key/data pairs in the map to a particular query point', ' public ArrayList <DataWrapper <PointInMetricSpace, DataType>> findKClosest (PointInMetricSpace query, int k) {', ' PQueueABCD <PointInMetricSpace, DataType> myQ = new PQueueABCD <PointInMetricSpace, DataType> (k);', ' root.findKClosest (query, myQ);', ' return myQ.done ();', ' }', ' ', ' // get the depth'] | [' public int depth () {', ' return root.depth (); ', ' }'] | ['}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', '', 'public class MTreeTester extends TestCase {', ' ', ' // compare two lists of strings to see if the contents are the same', ' private boolean compareStringSets (ArrayList <String> setOne, ArrayList <String> setTwo) {', ' ', ' // sort the sets and make sure they are the same', ' boolean returnVal = true;', ' if (setOne.size () == setTwo.size ()) {', ' Collections.sort (setOne);', ' Collections.sort (setTwo);', ' for (int i = 0; i < setOne.size (); i++) {', ' if (!setOne.get (i).equals (setTwo.get (i))) {', ' returnVal = false;', ' break; ', ' }', ' }', ' } else {', ' returnVal = false;', ' }', ' ', ' // print out the result', ' System.out.println ("**** Expected:");', ' for (int i = 0; i < setOne.size (); i++) {', ' System.out.format (setOne.get (i) + " ");', ' }', ' System.out.println ("\\n**** Got:");', ' for (int i = 0; i < setTwo.size (); i++) {', ' System.out.format (setTwo.get (i) + " ");', ' }', ' System.out.println ("");', ' ', ' return returnVal;', ' }', ' ', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST SIMPLE ONE DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testOneDimRangeQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.find (query, expectedQuerySize / 2);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.find (query, expectedQuerySize / 2);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (numPoints);', ' result1 = myTree.find (query, expectedQuerySize);', ' result2 = hisTree.find (query, expectedQuerySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // like the last one, but runs a top k', ' private void testOneDimTopKQuery (boolean orderThemOrNot, int minDepth,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (167);', ' IMTree <OneDimPoint, String> myTree = new SCMTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <OneDimPoint, String> hisTree = new MTree <OneDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = i / (numPoints * 1.0);', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' }', ' } else {', ' for (int i = 0; i < numPoints; i++) {', ' double nextOne = rn.nextDouble ();', ' myTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' hisTree.insert (new OneDimPoint (nextOne * numPoints), (new Double (nextOne * numPoints)).toString ());', ' } ', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' OneDimPoint query = new OneDimPoint (numPoints * 0.5);', ' ArrayList <DataWrapper <OneDimPoint, String>> result1 = myTree.findKClosest (query, querySize);', ' ArrayList <DataWrapper <OneDimPoint, String>> result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' query = new OneDimPoint (0);', ' result1 = myTree.findKClosest (query, querySize);', ' result2 = hisTree.findKClosest (query, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' /**', ' * THESE TWO HELPER METHODS TEST MULTI-DIMENSIONAL DATA', ' */', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimRangeQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, double expectedQuerySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' double dist1 = 0;', ' double dist2 = 0;', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' dist1 = Math.sqrt (numDims) * expectedQuerySize / 2.0;', ' dist2 = Math.sqrt (numDims) * expectedQuerySize;', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' // do a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, (int) expectedQuerySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = myTree.findKClosest (query2, (int) expectedQuerySize);', ' ', ' // find the distance to the furthest point in both cases', ' for (int i = 0; i < (int) expectedQuerySize; i++) {', ' double newDist = result1.get (i).getKey ().getDistance (query1);', ' if (newDist > dist1)', ' dist1 = newDist;', ' newDist = result2.get (i).getKey ().getDistance (query2);', ' if (newDist > dist2)', ' dist2 = newDist;', ' }', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a range query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.find (query1, dist1);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.find (query1, dist1);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.find (query2, dist2);', ' result2 = hisTree.find (query2, dist2);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' // puts the specified number of random points into a tree of the given node size', ' private void testMultiDimTopKQuery (boolean orderThemOrNot, int minDepth, int numDims,', ' int internalNodeSize, int leafNodeSize, int numPoints, int querySize) {', ' ', ' // create two trees', ' Random rn = new Random (133);', ' IMTree <MultiDimPoint, String> myTree = new SCMTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' IMTree <MultiDimPoint, String> hisTree = new MTree <MultiDimPoint, String> (internalNodeSize, leafNodeSize);', ' ', ' // these are the queries', ' MultiDimPoint query1;', ' MultiDimPoint query2;', ' ', ' // add a bunch of points', ' if (orderThemOrNot) {', ' ', ' for (int i = 0; i < numPoints; i++) {', ' SparseDoubleVector temp1 = new SparseDoubleVector (numDims, i);', ' SparseDoubleVector temp2 = new SparseDoubleVector (numDims, i);', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, the queries are simple', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, numPoints / 2));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' ', ' } else {', ' ', ' // create a bunch of random data', ' for (int i = 0; i < numPoints; i++) {', ' DenseDoubleVector temp1 = new DenseDoubleVector (numDims, 0.0);', ' DenseDoubleVector temp2 = new DenseDoubleVector (numDims, 0.0);', ' for (int j = 0; j < numDims; j++) {', ' double curVal = rn.nextDouble ();', ' try {', ' temp1.setItem (j, curVal);', ' temp2.setItem (j, curVal);', ' } catch (OutOfBoundsException e) {', ' System.out.println ("Error in test case? Why am I out of bounds?"); ', ' }', ' }', ' myTree.insert (new MultiDimPoint (temp1), temp1.toString ());', ' hisTree.insert (new MultiDimPoint (temp2), temp2.toString ());', ' }', ' ', ' // in this case, get the spheres first', ' query1 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.5));', ' query2 = new MultiDimPoint (new SparseDoubleVector (numDims, 0.0));', ' }', ' ', ' assertTrue ("Why was the tree not of depth at least " + minDepth, hisTree.depth () >= minDepth);', ' ', ' // run a top k query', ' ArrayList <DataWrapper <MultiDimPoint, String>> result1 = myTree.findKClosest (query1, querySize);', ' ArrayList <DataWrapper <MultiDimPoint, String>> result2 = hisTree.findKClosest (query1, querySize);', ' ', ' // check the results', ' ArrayList <String> setOne = new ArrayList <String> (), setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' ', ' // run a second range query', ' result1 = myTree.findKClosest (query2, querySize);', ' result2 = hisTree.findKClosest (query2, querySize);', ' ', ' // check the results', ' setOne = new ArrayList <String> ();', ' setTwo = new ArrayList <String> ();', ' for (int i = 0; i < result1.size (); i++) {', ' setOne.add (result1.get (i).getData ()); ', ' }', ' for (int i = 0; i < result2.size (); i++) {', ' setTwo.add (result2.get (i).getData ()); ', ' }', ' assertTrue (compareStringSets (setOne, setTwo));', ' }', ' ', ' ', ' /**', ' * "TIER 1" TESTS', ' * NONE OF THESE REQUIRE ANY SPLITS', ' */', ' public void testEasy1() {', ' testOneDimRangeQuery (true, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy2() {', ' testOneDimRangeQuery (false, 1, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy3() {', ' testOneDimRangeQuery (true, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy4() {', ' testOneDimRangeQuery (false, 1, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy5() {', ' testMultiDimRangeQuery (true, 1, 5, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy6() {', ' testMultiDimRangeQuery (false, 1, 10, 10, 10, 5, 2.1);', ' }', ' ', ' public void testEasy7() {', ' testMultiDimRangeQuery (true, 1, 5, 10000, 10000, 5000, 10);', ' }', ' ', ' public void testEasy8() {', ' testMultiDimRangeQuery (false, 1, 15, 10000, 10000, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 2" TESTS', ' * NONE OF THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testMod1() {', ' testOneDimRangeQuery (true, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod2() {', ' testOneDimRangeQuery (false, 2, 10, 10, 50, 5.1);', ' }', ' ', ' public void testMod3() {', ' testOneDimRangeQuery (true, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod4() {', ' testOneDimRangeQuery (false, 2, 20, 100, 1000, 10);', ' }', ' ', ' public void testMod5() {', ' testMultiDimRangeQuery (true, 2, 5, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod6() {', ' testMultiDimRangeQuery (false, 2, 10, 1000, 200, 10000, 2.1);', ' }', ' ', ' public void testMod7() {', ' testMultiDimRangeQuery (true, 2, 5, 10000, 100, 1000, 10);', ' }', ' ', ' public void testMod8() {', ' testMultiDimRangeQuery (false, 2, 15, 10000, 100, 1000, 4);', ' }', ' ', ' /**', ' * "TIER 3" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE', ' */', ' ', ' public void testHard1() {', ' testOneDimRangeQuery (true, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard2() {', ' testOneDimRangeQuery (false, 3, 10, 10, 500, 5.1);', ' }', ' ', ' public void testHard3() {', ' testOneDimRangeQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard4() {', ' testOneDimRangeQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard5() {', ' testMultiDimRangeQuery (true, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard6() {', ' testMultiDimRangeQuery (false, 3, 5, 5, 5, 100000, 2.1);', ' }', ' ', ' public void testHard7() {', ' testMultiDimRangeQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testHard8() {', ' testMultiDimRangeQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', ' ', ' /**', ' * "TIER 4" TESTS', ' * THESE REQUIRE A SPLIT OF AN INTERNAL NODE AND THEY TEST THE TOPK FUNCTIONALITY', ' */', ' ', ' public void testTopK1() {', ' testOneDimTopKQuery (true, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK2() {', ' testOneDimTopKQuery (false, 3, 10, 10, 500, 5);', ' }', ' ', ' public void testTopK3() {', ' testOneDimTopKQuery (true, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK4() {', ' testOneDimTopKQuery (false, 3, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK5() {', ' testMultiDimTopKQuery (true, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK6() {', ' testMultiDimTopKQuery (false, 3, 5, 5, 5, 100000, 2);', ' }', ' ', ' public void testTopK7() {', ' testMultiDimTopKQuery (true, 3, 15, 4, 4, 10000, 10);', ' }', ' ', ' public void testTopK8() {', ' testMultiDimTopKQuery (false, 3, 15, 4, 4, 10000, 4);', ' }', '}'] | [] | Function 'depth' used at line 804 is defined at line 31 and has a Long-Range dependency.
Global_Variable 'root' used at line 805 is defined at line 770 and has a Long-Range dependency. | {} | {'Function Long-Range': 1, 'Global_Variable Long-Range': 1} |
completion_java | TopKTester | 167 | 168 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {'] | [' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));'] | [' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Global_Variable 'left' used at line 167 is defined at line 136 and has a Long-Range dependency.
Global_Variable 'right' used at line 167 is defined at line 137 and has a Medium-Range dependency.
Global_Variable 'left' used at line 168 is defined at line 136 and has a Long-Range dependency.
Global_Variable 'right' used at line 168 is defined at line 137 and has a Long-Range dependency. | {} | {'Global_Variable Long-Range': 3, 'Global_Variable Medium-Range': 1} |
completion_java | TopKTester | 187 | 187 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep'] | [' left.makeLeftDeep ();'] | [' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Else Reasoning', 'usage_line': 187}, {'reason_category': 'If Body', 'usage_line': 187}] | Global_Variable 'left' used at line 187 is defined at line 136 and has a Long-Range dependency. | {'Else Reasoning': 1, 'If Body': 1} | {'Global_Variable Long-Range': 1} |
completion_java | TopKTester | 190 | 195 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree'] | [' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();'] | [' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Else Reasoning', 'usage_line': 190}, {'reason_category': 'If Body', 'usage_line': 190}, {'reason_category': 'Else Reasoning', 'usage_line': 191}, {'reason_category': 'If Body', 'usage_line': 191}, {'reason_category': 'Else Reasoning', 'usage_line': 192}, {'reason_category': 'If Body', 'usage_line': 192}, {'reason_category': 'Else Reasoning', 'usage_line': 193}, {'reason_category': 'If Body', 'usage_line': 193}, {'reason_category': 'Else Reasoning', 'usage_line': 194}, {'reason_category': 'If Body', 'usage_line': 194}, {'reason_category': 'Else Reasoning', 'usage_line': 195}, {'reason_category': 'If Body', 'usage_line': 195}] | Class 'AVLNode' used at line 190 is defined at line 28 and has a Long-Range dependency.
Global_Variable 'left' used at line 190 is defined at line 136 and has a Long-Range dependency.
Class 'AVLNode' used at line 191 is defined at line 28 and has a Long-Range dependency.
Global_Variable 'right' used at line 191 is defined at line 180 and has a Medium-Range dependency.
Variable 'oldLeft' used at line 192 is defined at line 190 and has a Short-Range dependency.
Global_Variable 'left' used at line 192 is defined at line 136 and has a Long-Range dependency.
Class 'Occupied' used at line 193 is defined at line 134 and has a Long-Range dependency.
Global_Variable 'val' used at line 193 is defined at line 138 and has a Long-Range dependency.
Variable 'oldLeft' used at line 193 is defined at line 190 and has a Short-Range dependency.
Global_Variable 'right' used at line 193 is defined at line 180 and has a Medium-Range dependency.
Variable 'oldLeft' used at line 194 is defined at line 190 and has a Short-Range dependency.
Global_Variable 'val' used at line 194 is defined at line 138 and has a Long-Range dependency.
Function 'setHeight' used at line 195 is defined at line 35 and has a Long-Range dependency. | {'Else Reasoning': 6, 'If Body': 6} | {'Class Long-Range': 3, 'Global_Variable Long-Range': 4, 'Global_Variable Medium-Range': 2, 'Variable Short-Range': 3, 'Function Long-Range': 1} |
completion_java | TopKTester | 217 | 217 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else'] | [' height = other;'] | [' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Else Reasoning', 'usage_line': 217}] | Variable 'other' used at line 217 is defined at line 213 and has a Short-Range dependency.
Global_Variable 'height' used at line 217 is defined at line 215 and has a Short-Range dependency. | {'Else Reasoning': 1} | {'Variable Short-Range': 1, 'Global_Variable Short-Range': 1} |
completion_java | TopKTester | 228 | 228 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first'] | [' left.makeLeftDeep ();'] | [' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Global_Variable 'left' used at line 228 is defined at line 136 and has a Long-Range dependency. | {} | {'Global_Variable Long-Range': 1} |
completion_java | TopKTester | 231 | 236 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing'] | [' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();'] | [' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Class 'AVLNode' used at line 231 is defined at line 28 and has a Long-Range dependency.
Global_Variable 'left' used at line 231 is defined at line 136 and has a Long-Range dependency.
Class 'AVLNode' used at line 232 is defined at line 28 and has a Long-Range dependency.
Global_Variable 'right' used at line 232 is defined at line 137 and has a Long-Range dependency.
Variable 'oldLeft' used at line 233 is defined at line 231 and has a Short-Range dependency.
Global_Variable 'left' used at line 233 is defined at line 136 and has a Long-Range dependency.
Class 'Occupied' used at line 234 is defined at line 134 and has a Long-Range dependency.
Global_Variable 'val' used at line 234 is defined at line 138 and has a Long-Range dependency.
Variable 'oldLeft' used at line 234 is defined at line 231 and has a Short-Range dependency.
Global_Variable 'right' used at line 234 is defined at line 137 and has a Long-Range dependency.
Variable 'oldLeft' used at line 235 is defined at line 231 and has a Short-Range dependency.
Global_Variable 'val' used at line 235 is defined at line 138 and has a Long-Range dependency.
Function 'setHeight' used at line 236 is defined at line 210 and has a Medium-Range dependency. | {} | {'Class Long-Range': 3, 'Global_Variable Long-Range': 6, 'Variable Short-Range': 3, 'Function Medium-Range': 1} |
completion_java | TopKTester | 242 | 242 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first'] | [' right.makeRightDeep ();'] | [' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Global_Variable 'right' used at line 242 is defined at line 137 and has a Long-Range dependency. | {} | {'Global_Variable Long-Range': 1} |
completion_java | TopKTester | 245 | 250 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing'] | [' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();'] | [' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Class 'AVLNode' used at line 245 is defined at line 28 and has a Long-Range dependency.
Global_Variable 'left' used at line 245 is defined at line 136 and has a Long-Range dependency.
Class 'AVLNode' used at line 246 is defined at line 28 and has a Long-Range dependency.
Global_Variable 'right' used at line 246 is defined at line 137 and has a Long-Range dependency.
Class 'Occupied' used at line 247 is defined at line 134 and has a Long-Range dependency.
Global_Variable 'val' used at line 247 is defined at line 138 and has a Long-Range dependency.
Variable 'oldLeft' used at line 247 is defined at line 245 and has a Short-Range dependency.
Variable 'oldRight' used at line 247 is defined at line 246 and has a Short-Range dependency.
Global_Variable 'left' used at line 247 is defined at line 136 and has a Long-Range dependency.
Variable 'oldRight' used at line 248 is defined at line 246 and has a Short-Range dependency.
Global_Variable 'right' used at line 248 is defined at line 137 and has a Long-Range dependency.
Variable 'oldRight' used at line 249 is defined at line 246 and has a Short-Range dependency.
Global_Variable 'val' used at line 249 is defined at line 138 and has a Long-Range dependency.
Function 'setHeight' used at line 250 is defined at line 210 and has a Long-Range dependency. | {} | {'Class Long-Range': 3, 'Global_Variable Long-Range': 6, 'Variable Short-Range': 4, 'Function Long-Range': 1} |
completion_java | TopKTester | 255 | 255 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' '] | [' if (left.getHeight () >= right.getHeight ())'] | [' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Condition', 'usage_line': 255}] | Global_Variable 'left' used at line 255 is defined at line 136 and has a Long-Range dependency.
Global_Variable 'right' used at line 255 is defined at line 137 and has a Long-Range dependency. | {'If Condition': 1} | {'Global_Variable Long-Range': 2} |
completion_java | TopKTester | 268 | 268 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' '] | [' if (right.getHeight () >= left.getHeight ())'] | [' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Condition', 'usage_line': 268}] | Global_Variable 'right' used at line 268 is defined at line 137 and has a Long-Range dependency.
Global_Variable 'left' used at line 268 is defined at line 136 and has a Long-Range dependency. | {'If Condition': 1} | {'Global_Variable Long-Range': 2} |
completion_java | TopKTester | 271 | 276 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' '] | [' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();'] | [' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Class 'AVLNode' used at line 271 is defined at line 28 and has a Long-Range dependency.
Global_Variable 'left' used at line 271 is defined at line 136 and has a Long-Range dependency.
Class 'AVLNode' used at line 272 is defined at line 28 and has a Long-Range dependency.
Global_Variable 'right' used at line 272 is defined at line 137 and has a Long-Range dependency.
Variable 'oldLeft' used at line 273 is defined at line 271 and has a Short-Range dependency.
Global_Variable 'left' used at line 273 is defined at line 136 and has a Long-Range dependency.
Class 'Occupied' used at line 274 is defined at line 134 and has a Long-Range dependency.
Global_Variable 'val' used at line 274 is defined at line 138 and has a Long-Range dependency.
Variable 'oldLeft' used at line 274 is defined at line 271 and has a Short-Range dependency.
Variable 'oldRight' used at line 274 is defined at line 272 and has a Short-Range dependency.
Global_Variable 'right' used at line 274 is defined at line 137 and has a Long-Range dependency.
Variable 'oldLeft' used at line 275 is defined at line 271 and has a Short-Range dependency.
Global_Variable 'val' used at line 275 is defined at line 138 and has a Long-Range dependency.
Function 'setHeight' used at line 276 is defined at line 210 and has a Long-Range dependency. | {} | {'Class Long-Range': 3, 'Global_Variable Long-Range': 6, 'Variable Short-Range': 4, 'Function Long-Range': 1} |
completion_java | TopKTester | 292 | 292 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {'] | [' right = right.insert (myKey, myVal); '] | [' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Else Reasoning', 'usage_line': 292}] | Global_Variable 'right' used at line 292 is defined at line 137 and has a Long-Range dependency.
Variable 'myKey' used at line 292 is defined at line 287 and has a Short-Range dependency.
Variable 'myVal' used at line 292 is defined at line 287 and has a Short-Range dependency. | {'Else Reasoning': 1} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 2} |
completion_java | TopKTester | 297 | 298 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();'] | [' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();'] | [' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Elif Condition', 'usage_line': 297}, {'reason_category': 'Elif Body', 'usage_line': 298}] | Global_Variable 'right' used at line 297 is defined at line 292 and has a Short-Range dependency.
Global_Variable 'left' used at line 297 is defined at line 290 and has a Short-Range dependency.
Function 'raiseRight' used at line 298 is defined at line 239 and has a Long-Range dependency. | {'Elif Condition': 1, 'Elif Body': 1} | {'Global_Variable Short-Range': 2, 'Function Long-Range': 1} |
completion_java | TopKTester | 352 | 353 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;'] | [" while (checkMe.charAt (startPos) != '(')", ' startPos++;'] | [' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 352}, {'reason_category': 'Loop Body', 'usage_line': 353}] | Variable 'checkMe' used at line 352 is defined at line 348 and has a Short-Range dependency.
Variable 'startPos' used at line 352 is defined at line 351 and has a Short-Range dependency.
Variable 'startPos' used at line 353 is defined at line 351 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 1} | {'Variable Short-Range': 3} |
completion_java | TopKTester | 369 | 370 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;'] | [" else if (checkMe.charAt (i) == ')')", ' rParens++;'] | [' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 369}, {'reason_category': 'Elif Condition', 'usage_line': 369}, {'reason_category': 'Loop Body', 'usage_line': 370}, {'reason_category': 'Elif Body', 'usage_line': 370}] | Variable 'checkMe' used at line 369 is defined at line 348 and has a Medium-Range dependency.
Variable 'i' used at line 369 is defined at line 364 and has a Short-Range dependency.
Variable 'rParens' used at line 370 is defined at line 363 and has a Short-Range dependency. | {'Loop Body': 2, 'Elif Condition': 1, 'Elif Body': 1} | {'Variable Medium-Range': 1, 'Variable Short-Range': 2} |
completion_java | TopKTester | 373 | 373 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal'] | [' if (lParens == rParens && lParens > 0) {'] | [' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 373}, {'reason_category': 'If Condition', 'usage_line': 373}] | Variable 'lParens' used at line 373 is defined at line 362 and has a Medium-Range dependency.
Variable 'rParens' used at line 373 is defined at line 363 and has a Short-Range dependency. | {'Loop Body': 1, 'If Condition': 1} | {'Variable Medium-Range': 1, 'Variable Short-Range': 1} |
completion_java | TopKTester | 377 | 381 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {'] | [' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' '] | [' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 377}, {'reason_category': 'If Body', 'usage_line': 377}, {'reason_category': 'Loop Body', 'usage_line': 378}, {'reason_category': 'If Body', 'usage_line': 378}, {'reason_category': 'Loop Body', 'usage_line': 379}, {'reason_category': 'If Body', 'usage_line': 379}, {'reason_category': 'If Body', 'usage_line': 380}, {'reason_category': 'Loop Body', 'usage_line': 380}, {'reason_category': 'Loop Body', 'usage_line': 381}] | Function 'checkHeight' used at line 377 is defined at line 348 and has a Medium-Range dependency.
Variable 'checkMe' used at line 377 is defined at line 348 and has a Medium-Range dependency.
Variable 'startPos' used at line 377 is defined at line 351 and has a Medium-Range dependency.
Variable 'i' used at line 377 is defined at line 364 and has a Medium-Range dependency.
Variable 'leftDepth' used at line 377 is defined at line 356 and has a Medium-Range dependency.
Variable 'i' used at line 378 is defined at line 364 and has a Medium-Range dependency.
Variable 'startPos' used at line 378 is defined at line 351 and has a Medium-Range dependency.
Variable 'lParens' used at line 379 is defined at line 362 and has a Medium-Range dependency.
Variable 'rParens' used at line 380 is defined at line 363 and has a Medium-Range dependency. | {'Loop Body': 5, 'If Body': 4} | {'Function Medium-Range': 1, 'Variable Medium-Range': 8} |
completion_java | TopKTester | 384 | 386 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {'] | [' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;'] | [' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 384}, {'reason_category': 'Else Reasoning', 'usage_line': 384}, {'reason_category': 'Loop Body', 'usage_line': 385}, {'reason_category': 'Else Reasoning', 'usage_line': 385}, {'reason_category': 'Loop Body', 'usage_line': 386}, {'reason_category': 'Else Reasoning', 'usage_line': 386}] | Function 'checkHeight' used at line 384 is defined at line 348 and has a Long-Range dependency.
Variable 'checkMe' used at line 384 is defined at line 348 and has a Long-Range dependency.
Variable 'startPos' used at line 384 is defined at line 378 and has a Short-Range dependency.
Variable 'i' used at line 384 is defined at line 364 and has a Medium-Range dependency.
Variable 'rightDepth' used at line 384 is defined at line 359 and has a Medium-Range dependency.
Variable 'i' used at line 385 is defined at line 364 and has a Medium-Range dependency.
Variable 'startPos' used at line 385 is defined at line 378 and has a Short-Range dependency. | {'Loop Body': 3, 'Else Reasoning': 3} | {'Function Long-Range': 1, 'Variable Long-Range': 1, 'Variable Short-Range': 2, 'Variable Medium-Range': 3} |
completion_java | TopKTester | 392 | 392 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree'] | [' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)'] | [' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Condition', 'usage_line': 392}] | Variable 'leftDepth' used at line 392 is defined at line 356 and has a Long-Range dependency.
Variable 'rightDepth' used at line 392 is defined at line 359 and has a Long-Range dependency. | {'If Condition': 1} | {'Variable Long-Range': 2} |
completion_java | TopKTester | 396 | 396 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )'] | [" while (checkMe.charAt (startPos) != ')')"] | [' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 396}] | Variable 'checkMe' used at line 396 is defined at line 348 and has a Long-Range dependency.
Variable 'startPos' used at line 396 is defined at line 351 and has a Long-Range dependency. | {'Define Stop Criteria': 1} | {'Variable Long-Range': 2} |
completion_java | TopKTester | 426 | 429 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {'] | [' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();'] | [' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 426}, {'reason_category': 'If Body', 'usage_line': 427}, {'reason_category': 'If Condition', 'usage_line': 428}, {'reason_category': 'If Body', 'usage_line': 428}, {'reason_category': 'If Body', 'usage_line': 429}] | Global_Variable 'myTree' used at line 426 is defined at line 413 and has a Medium-Range dependency.
Variable 'score' used at line 426 is defined at line 424 and has a Short-Range dependency.
Variable 'value' used at line 426 is defined at line 424 and has a Short-Range dependency.
Global_Variable 'spaceLeft' used at line 427 is defined at line 412 and has a Medium-Range dependency.
Global_Variable 'spaceLeft' used at line 428 is defined at line 412 and has a Medium-Range dependency.
Global_Variable 'myTree' used at line 429 is defined at line 413 and has a Medium-Range dependency.
Global_Variable 'cutoff' used at line 429 is defined at line 414 and has a Medium-Range dependency. | {'If Body': 4, 'If Condition': 1} | {'Global_Variable Medium-Range': 5, 'Variable Short-Range': 2} |
completion_java | TopKTester | 433 | 435 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {'] | [' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;'] | [' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 433}, {'reason_category': 'If Body', 'usage_line': 434}, {'reason_category': 'If Body', 'usage_line': 435}] | Global_Variable 'myTree' used at line 433 is defined at line 413 and has a Medium-Range dependency.
Global_Variable 'myTree' used at line 434 is defined at line 413 and has a Medium-Range dependency.
Global_Variable 'cutoff' used at line 434 is defined at line 429 and has a Short-Range dependency.
Global_Variable 'spaceLeft' used at line 435 is defined at line 412 and has a Medium-Range dependency. | {'If Body': 3} | {'Global_Variable Medium-Range': 3, 'Global_Variable Short-Range': 1} |
completion_java | TopKTester | 467 | 471 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {'] | [' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;'] | [' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 467}, {'reason_category': 'Loop Body', 'usage_line': 468}, {'reason_category': 'Loop Body', 'usage_line': 469}, {'reason_category': 'Loop Body', 'usage_line': 470}, {'reason_category': 'Loop Body', 'usage_line': 471}] | Variable 'i' used at line 467 is defined at line 467 and has a Short-Range dependency.
Variable 'list' used at line 467 is defined at line 466 and has a Short-Range dependency.
Variable 'i' used at line 468 is defined at line 467 and has a Short-Range dependency.
Global_Variable 'shuffler' used at line 468 is defined at line 465 and has a Short-Range dependency.
Variable 'list' used at line 468 is defined at line 466 and has a Short-Range dependency.
Variable 'list' used at line 469 is defined at line 466 and has a Short-Range dependency.
Variable 'i' used at line 469 is defined at line 467 and has a Short-Range dependency.
Variable 'list' used at line 470 is defined at line 466 and has a Short-Range dependency.
Variable 'pos' used at line 470 is defined at line 468 and has a Short-Range dependency.
Variable 'i' used at line 470 is defined at line 467 and has a Short-Range dependency.
Variable 'temp' used at line 471 is defined at line 469 and has a Short-Range dependency.
Variable 'list' used at line 471 is defined at line 470 and has a Short-Range dependency.
Variable 'pos' used at line 471 is defined at line 468 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 4} | {'Variable Short-Range': 12, 'Global_Variable Short-Range': 1} |
completion_java | TopKTester | 492 | 497 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];'] | [' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }'] | [' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 492}, {'reason_category': 'Loop Body', 'usage_line': 493}, {'reason_category': 'If Condition', 'usage_line': 493}, {'reason_category': 'If Body', 'usage_line': 494}, {'reason_category': 'Loop Body', 'usage_line': 494}, {'reason_category': 'Else Reasoning', 'usage_line': 495}, {'reason_category': 'Loop Body', 'usage_line': 495}, {'reason_category': 'Else Reasoning', 'usage_line': 496}, {'reason_category': 'Loop Body', 'usage_line': 496}, {'reason_category': 'Loop Body', 'usage_line': 497}] | Variable 'i' used at line 492 is defined at line 492 and has a Short-Range dependency.
Variable 'numInserts' used at line 492 is defined at line 481 and has a Medium-Range dependency.
Variable 'reverseOrNot' used at line 493 is defined at line 487 and has a Short-Range dependency.
Variable 'numInserts' used at line 494 is defined at line 481 and has a Medium-Range dependency.
Variable 'i' used at line 494 is defined at line 492 and has a Short-Range dependency.
Variable 'list' used at line 494 is defined at line 491 and has a Short-Range dependency.
Variable 'i' used at line 496 is defined at line 492 and has a Short-Range dependency.
Variable 'list' used at line 496 is defined at line 494 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 5, 'If Condition': 1, 'If Body': 1, 'Else Reasoning': 2} | {'Variable Short-Range': 6, 'Variable Medium-Range': 2} |
completion_java | TopKTester | 501 | 501 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)'] | [' shuffle (list);'] | [' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 501}] | Function 'shuffle' used at line 501 is defined at line 466 and has a Long-Range dependency.
Variable 'list' used at line 501 is defined at line 491 and has a Short-Range dependency. | {'If Body': 1} | {'Function Long-Range': 1, 'Variable Short-Range': 1} |
completion_java | TopKTester | 529 | 529 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {'] | [' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);'] | [' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 529}, {'reason_category': 'If Body', 'usage_line': 529}, {'reason_category': 'Else Reasoning', 'usage_line': 529}] | Variable 'k' used at line 529 is defined at line 481 and has a Long-Range dependency.
Variable 'score' used at line 529 is defined at line 512 and has a Medium-Range dependency. | {'Loop Body': 1, 'If Body': 1, 'Else Reasoning': 1} | {'Variable Long-Range': 1, 'Variable Medium-Range': 1} |
completion_java | TopKTester | 541 | 541 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)'] | [' k = numInserts;'] | [' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 541}] | Variable 'numInserts' used at line 541 is defined at line 481 and has a Long-Range dependency.
Variable 'k' used at line 541 is defined at line 481 and has a Long-Range dependency. | {'If Body': 1} | {'Variable Long-Range': 2} |
completion_java | TopKTester | 544 | 544 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size'] | [' assertEquals (retVal.size (), k);'] | [' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Variable 'retVal' used at line 544 is defined at line 536 and has a Short-Range dependency.
Variable 'k' used at line 544 is defined at line 541 and has a Short-Range dependency. | {} | {'Variable Short-Range': 2} |
completion_java | TopKTester | 562 | 569 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints'] | [' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }'] | [' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 564}, {'reason_category': 'Loop Body', 'usage_line': 565}, {'reason_category': 'If Condition', 'usage_line': 565}, {'reason_category': 'Loop Body', 'usage_line': 566}, {'reason_category': 'If Body', 'usage_line': 566}, {'reason_category': 'Else Reasoning', 'usage_line': 567}, {'reason_category': 'Loop Body', 'usage_line': 567}, {'reason_category': 'Else Reasoning', 'usage_line': 568}, {'reason_category': 'Loop Body', 'usage_line': 568}, {'reason_category': 'Loop Body', 'usage_line': 569}] | Class 'AVLTopKMachine' used at line 562 is defined at line 410 and has a Long-Range dependency.
Variable 'k' used at line 562 is defined at line 553 and has a Short-Range dependency.
Variable 'numInserts' used at line 563 is defined at line 553 and has a Short-Range dependency.
Variable 'i' used at line 564 is defined at line 564 and has a Short-Range dependency.
Variable 'numInserts' used at line 564 is defined at line 553 and has a Medium-Range dependency.
Variable 'reverseOrNot' used at line 565 is defined at line 559 and has a Short-Range dependency.
Variable 'numInserts' used at line 566 is defined at line 553 and has a Medium-Range dependency.
Variable 'i' used at line 566 is defined at line 564 and has a Short-Range dependency.
Variable 'list' used at line 566 is defined at line 563 and has a Short-Range dependency.
Variable 'i' used at line 568 is defined at line 564 and has a Short-Range dependency.
Variable 'list' used at line 568 is defined at line 566 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 5, 'If Condition': 1, 'If Body': 1, 'Else Reasoning': 2} | {'Class Long-Range': 1, 'Variable Short-Range': 8, 'Variable Medium-Range': 2} |
completion_java | TopKTester | 572 | 573 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list'] | [' if (randomOrNot)', ' shuffle (list);'] | [' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Condition', 'usage_line': 572}, {'reason_category': 'If Loop', 'usage_line': 573}] | Variable 'randomOrNot' used at line 572 is defined at line 557 and has a Medium-Range dependency.
Function 'shuffle' used at line 573 is defined at line 466 and has a Long-Range dependency.
Variable 'list' used at line 573 is defined at line 563 and has a Short-Range dependency. | {'If Condition': 1} | {'Variable Medium-Range': 1, 'Function Long-Range': 1, 'Variable Short-Range': 1} |
completion_java | TopKTester | 582 | 584 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {'] | [' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());'] | [' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 582}, {'reason_category': 'Loop Body', 'usage_line': 582}, {'reason_category': 'Loop Body', 'usage_line': 583}, {'reason_category': 'If Body', 'usage_line': 583}, {'reason_category': 'Loop Body', 'usage_line': 584}, {'reason_category': 'If Body', 'usage_line': 584}] | Class 'IsBalanced' used at line 582 is defined at line 344 and has a Long-Range dependency.
Function 'IsBalanced.checkHeight' used at line 584 is defined at line 348 and has a Long-Range dependency.
Function 'AVLTopKMachine.toString' used at line 584 is defined at line 445 and has a Long-Range dependency. | {'If Body': 3, 'Loop Body': 3} | {'Class Long-Range': 1, 'Function Long-Range': 2} |
completion_java | TopKTester | 593 | 593 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {'] | [' temp.checkHeight (testMe.toString ());'] | [' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 593}] | Function 'IsBalanced.checkHeight' used at line 593 is defined at line 348 and has a Long-Range dependency.
Function 'AVLTopKMachine.toString' used at line 593 is defined at line 445 and has a Long-Range dependency. | {'Loop Body': 1} | {'Function Long-Range': 2} |
completion_java | SparseArrayTester | 16 | 16 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */'] | [' int getIndex();'] | ['', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | null | {} | null |
completion_java | SparseArrayTester | 23 | 23 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */'] | [' T getData();'] | ['}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | null | {} | null |
completion_java | SparseArrayTester | 33 | 33 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */'] | [' void put (int position, T element);'] | ['', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | null | {} | null |
completion_java | SparseArrayTester | 41 | 41 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */'] | [' T get (int position);'] | ['', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | null | {} | null |
completion_java | SparseArrayTester | 48 | 48 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */'] | [' Iterator<IIndexedData<T>> iterator ();'] | ['}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | null | {} | null |
completion_java | SparseArrayTester | 65 | 65 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {'] | [' return (curIdx+1) < numElements;'] | [' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | Global_Variable 'curIdx' used at line 65 is defined at line 52 and has a Medium-Range dependency.
Global_Variable 'numElements' used at line 65 is defined at line 53 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 2} |
completion_java | SparseArrayTester | 88 | 89 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];'] | [' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; '] | [' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 88}, {'reason_category': 'Loop Body', 'usage_line': 89}] | Variable 'i' used at line 88 is defined at line 88 and has a Short-Range dependency.
Global_Variable 'numElements' used at line 88 is defined at line 81 and has a Short-Range dependency.
Global_Variable 'indices' used at line 89 is defined at line 79 and has a Short-Range dependency.
Variable 'i' used at line 89 is defined at line 88 and has a Short-Range dependency.
Variable 'temp' used at line 89 is defined at line 87 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 1} | {'Variable Short-Range': 3, 'Global_Variable Short-Range': 2} |
completion_java | SparseArrayTester | 91 | 92 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }'] | [' indices = temp;', ' lastSlot *= 2;'] | [' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | Variable 'temp' used at line 91 is defined at line 87 and has a Short-Range dependency.
Global_Variable 'indices' used at line 91 is defined at line 79 and has a Medium-Range dependency.
Global_Variable 'lastSlot' used at line 92 is defined at line 82 and has a Short-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Medium-Range': 1, 'Global_Variable Short-Range': 1} |
completion_java | SparseArrayTester | 111 | 112 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {'] | [' data.add (element);', ' indices[numElements] = position;'] | [' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 111}, {'reason_category': 'If Body', 'usage_line': 112}] | Global_Variable 'data' used at line 111 is defined at line 80 and has a Long-Range dependency.
Variable 'element' used at line 111 is defined at line 107 and has a Short-Range dependency.
Variable 'position' used at line 112 is defined at line 107 and has a Short-Range dependency.
Global_Variable 'indices' used at line 112 is defined at line 79 and has a Long-Range dependency.
Global_Variable 'numElements' used at line 112 is defined at line 81 and has a Long-Range dependency. | {'If Body': 2} | {'Global_Variable Long-Range': 3, 'Variable Short-Range': 2} |
completion_java | SparseArrayTester | 118 | 123 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position'] | [' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }'] | [' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'Else Reasoning', 'usage_line': 118}, {'reason_category': 'Define Stop Criteria', 'usage_line': 118}, {'reason_category': 'Else Reasoning', 'usage_line': 119}, {'reason_category': 'Loop Body', 'usage_line': 119}, {'reason_category': 'If Condition', 'usage_line': 119}, {'reason_category': 'Else Reasoning', 'usage_line': 120}, {'reason_category': 'Loop Body', 'usage_line': 120}, {'reason_category': 'If Body', 'usage_line': 120}, {'reason_category': 'Else Reasoning', 'usage_line': 121}, {'reason_category': 'Loop Body', 'usage_line': 121}, {'reason_category': 'If Body', 'usage_line': 121}, {'reason_category': 'Else Reasoning', 'usage_line': 122}, {'reason_category': 'Loop Body', 'usage_line': 122}, {'reason_category': 'If Body', 'usage_line': 122}, {'reason_category': 'Else Reasoning', 'usage_line': 123}, {'reason_category': 'Loop Body', 'usage_line': 123}] | Variable 'i' used at line 118 is defined at line 118 and has a Short-Range dependency.
Global_Variable 'numElements' used at line 118 is defined at line 81 and has a Long-Range dependency.
Global_Variable 'indices' used at line 119 is defined at line 112 and has a Short-Range dependency.
Variable 'i' used at line 119 is defined at line 118 and has a Short-Range dependency.
Variable 'position' used at line 119 is defined at line 107 and has a Medium-Range dependency.
Global_Variable 'data' used at line 120 is defined at line 80 and has a Long-Range dependency.
Variable 'element' used at line 120 is defined at line 107 and has a Medium-Range dependency.
Variable 'i' used at line 120 is defined at line 118 and has a Short-Range dependency. | {'Else Reasoning': 6, 'Define Stop Criteria': 1, 'Loop Body': 5, 'If Condition': 1, 'If Body': 3} | {'Variable Short-Range': 3, 'Global_Variable Long-Range': 2, 'Global_Variable Short-Range': 1, 'Variable Medium-Range': 2} |
completion_java | SparseArrayTester | 119 | 122 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {'] | [' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }'] | [' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'Else Reasoning', 'usage_line': 119}, {'reason_category': 'Loop Body', 'usage_line': 119}, {'reason_category': 'If Condition', 'usage_line': 119}, {'reason_category': 'Else Reasoning', 'usage_line': 120}, {'reason_category': 'Loop Body', 'usage_line': 120}, {'reason_category': 'If Body', 'usage_line': 120}, {'reason_category': 'Else Reasoning', 'usage_line': 121}, {'reason_category': 'Loop Body', 'usage_line': 121}, {'reason_category': 'If Body', 'usage_line': 121}, {'reason_category': 'Else Reasoning', 'usage_line': 122}, {'reason_category': 'Loop Body', 'usage_line': 122}, {'reason_category': 'If Body', 'usage_line': 122}] | Global_Variable 'indices' used at line 119 is defined at line 112 and has a Short-Range dependency.
Variable 'i' used at line 119 is defined at line 118 and has a Short-Range dependency.
Variable 'position' used at line 119 is defined at line 107 and has a Medium-Range dependency.
Global_Variable 'data' used at line 120 is defined at line 80 and has a Long-Range dependency.
Variable 'element' used at line 120 is defined at line 107 and has a Medium-Range dependency.
Variable 'i' used at line 120 is defined at line 118 and has a Short-Range dependency. | {'Else Reasoning': 4, 'Loop Body': 4, 'If Condition': 1, 'If Body': 3} | {'Global_Variable Short-Range': 1, 'Variable Short-Range': 2, 'Variable Medium-Range': 2, 'Global_Variable Long-Range': 1} |
completion_java | SparseArrayTester | 120 | 120 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {'] | [' data.setElementAt (element, i);'] | [' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'Else Reasoning', 'usage_line': 120}, {'reason_category': 'Loop Body', 'usage_line': 120}, {'reason_category': 'If Body', 'usage_line': 120}] | Global_Variable 'data' used at line 120 is defined at line 80 and has a Long-Range dependency.
Variable 'element' used at line 120 is defined at line 107 and has a Medium-Range dependency.
Variable 'i' used at line 120 is defined at line 118 and has a Short-Range dependency. | {'Else Reasoning': 1, 'Loop Body': 1, 'If Body': 1} | {'Global_Variable Long-Range': 1, 'Variable Medium-Range': 1, 'Variable Short-Range': 1} |
completion_java | SparseArrayTester | 128 | 128 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {'] | [' indices[pos] = indices[pos - 1];'] | [' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'Else Reasoning', 'usage_line': 128}, {'reason_category': 'Loop Body', 'usage_line': 128}] | Global_Variable 'indices' used at line 128 is defined at line 112 and has a Medium-Range dependency.
Variable 'pos' used at line 128 is defined at line 127 and has a Short-Range dependency. | {'Else Reasoning': 1, 'Loop Body': 1} | {'Global_Variable Medium-Range': 1, 'Variable Short-Range': 1} |
completion_java | SparseArrayTester | 130 | 130 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }'] | [' indices[pos] = position;'] | [' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'Else Reasoning', 'usage_line': 130}] | Variable 'position' used at line 130 is defined at line 107 and has a Medium-Range dependency.
Global_Variable 'indices' used at line 130 is defined at line 112 and has a Medium-Range dependency.
Variable 'pos' used at line 130 is defined at line 126 and has a Short-Range dependency. | {'Else Reasoning': 1} | {'Variable Medium-Range': 1, 'Global_Variable Medium-Range': 1, 'Variable Short-Range': 1} |
completion_java | SparseArrayTester | 131 | 131 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;'] | [' data.add (pos, element);'] | [' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'Else Reasoning', 'usage_line': 131}] | Global_Variable 'data' used at line 131 is defined at line 80 and has a Long-Range dependency.
Variable 'pos' used at line 131 is defined at line 126 and has a Short-Range dependency.
Variable 'element' used at line 131 is defined at line 107 and has a Medium-Range dependency. | {'Else Reasoning': 1} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 1, 'Variable Medium-Range': 1} |
completion_java | SparseArrayTester | 130 | 131 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }'] | [' indices[pos] = position;', ' data.add (pos, element);'] | [' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'Else Reasoning', 'usage_line': 130}, {'reason_category': 'Else Reasoning', 'usage_line': 131}] | Variable 'position' used at line 130 is defined at line 107 and has a Medium-Range dependency.
Global_Variable 'indices' used at line 130 is defined at line 112 and has a Medium-Range dependency.
Variable 'pos' used at line 130 is defined at line 126 and has a Short-Range dependency.
Global_Variable 'data' used at line 131 is defined at line 80 and has a Long-Range dependency.
Variable 'pos' used at line 131 is defined at line 126 and has a Short-Range dependency.
Variable 'element' used at line 131 is defined at line 107 and has a Medium-Range dependency. | {'Else Reasoning': 2} | {'Variable Medium-Range': 2, 'Global_Variable Medium-Range': 1, 'Variable Short-Range': 2, 'Global_Variable Long-Range': 1} |
completion_java | SparseArrayTester | 136 | 136 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) '] | [' doubleCapacity ();'] | [' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 136}] | Function 'doubleCapacity' used at line 136 is defined at line 85 and has a Long-Range dependency. | {'If Body': 1} | {'Function Long-Range': 1} |
completion_java | SparseArrayTester | 142 | 142 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want'] | [' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);'] | [' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 142}] | Global_Variable 'lastSlotReturned' used at line 142 is defined at line 83 and has a Long-Range dependency.
Global_Variable 'indices' used at line 142 is defined at line 79 and has a Long-Range dependency.
Variable 'position' used at line 142 is defined at line 139 and has a Short-Range dependency. | {'Define Stop Criteria': 1} | {'Global_Variable Long-Range': 2, 'Variable Short-Range': 1} |
completion_java | SparseArrayTester | 145 | 145 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want'] | [' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);'] | [' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 145}] | Global_Variable 'lastSlotReturned' used at line 145 is defined at line 83 and has a Long-Range dependency.
Global_Variable 'numElements' used at line 145 is defined at line 81 and has a Long-Range dependency.
Global_Variable 'indices' used at line 145 is defined at line 79 and has a Long-Range dependency.
Variable 'position' used at line 145 is defined at line 139 and has a Short-Range dependency. | {'Define Stop Criteria': 1} | {'Global_Variable Long-Range': 3, 'Variable Short-Range': 1} |
completion_java | SparseArrayTester | 148 | 148 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy'] | [' if (lastSlotReturned == -1)'] | [' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'If Condition', 'usage_line': 148}] | Global_Variable 'lastSlotReturned' used at line 148 is defined at line 83 and has a Long-Range dependency. | {'If Condition': 1} | {'Global_Variable Long-Range': 1} |
completion_java | SparseArrayTester | 152 | 152 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it"] | [' if (indices[lastSlotReturned] != position)'] | [' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'If Condition', 'usage_line': 152}] | Global_Variable 'indices' used at line 152 is defined at line 79 and has a Long-Range dependency.
Global_Variable 'lastSlotReturned' used at line 152 is defined at line 83 and has a Long-Range dependency.
Variable 'position' used at line 152 is defined at line 139 and has a Medium-Range dependency. | {'If Condition': 1} | {'Global_Variable Long-Range': 2, 'Variable Medium-Range': 1} |
completion_java | SparseArrayTester | 156 | 156 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!'] | [' return data.get(lastSlotReturned);'] | [' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | Global_Variable 'data' used at line 156 is defined at line 80 and has a Long-Range dependency.
Global_Variable 'lastSlotReturned' used at line 156 is defined at line 83 and has a Long-Range dependency. | {} | {'Global_Variable Long-Range': 2} |
completion_java | SparseArrayTester | 168 | 168 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {'] | [' array.put(position, element);'] | [' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | Global_Variable 'array' used at line 168 is defined at line 161 and has a Short-Range dependency.
Variable 'position' used at line 168 is defined at line 167 and has a Short-Range dependency.
Variable 'element' used at line 168 is defined at line 167 and has a Short-Range dependency. | {} | {'Global_Variable Short-Range': 1, 'Variable Short-Range': 2} |
completion_java | SparseArrayTester | 172 | 172 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {'] | [' return array.get(position);'] | [' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | Global_Variable 'array' used at line 172 is defined at line 161 and has a Medium-Range dependency.
Variable 'position' used at line 172 is defined at line 171 and has a Short-Range dependency. | {} | {'Global_Variable Medium-Range': 1, 'Variable Short-Range': 1} |
completion_java | DoubleVectorTester | 32 | 42 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");'] | [' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' '] | [' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 32}, {'reason_category': 'Loop Body', 'usage_line': 33}, {'reason_category': 'Loop Body', 'usage_line': 34}, {'reason_category': 'If Condition', 'usage_line': 35}, {'reason_category': 'Loop Body', 'usage_line': 35}, {'reason_category': 'If Body', 'usage_line': 36}, {'reason_category': 'Loop Body', 'usage_line': 36}, {'reason_category': 'Loop Body', 'usage_line': 37}, {'reason_category': 'Loop Body', 'usage_line': 38}] | Variable 'i' used at line 32 is defined at line 32 and has a Short-Range dependency.
Function 'getLength' used at line 32 is defined at line 20 and has a Medium-Range dependency.
Function 'getItem' used at line 33 is defined at line 18 and has a Medium-Range dependency.
Variable 'i' used at line 33 is defined at line 32 and has a Short-Range dependency.
Variable 'i' used at line 35 is defined at line 32 and has a Short-Range dependency.
Variable 'returnVal' used at line 36 is defined at line 31 and has a Short-Range dependency.
Variable 'returnVal' used at line 38 is defined at line 36 and has a Short-Range dependency.
Variable 'curItem' used at line 38 is defined at line 33 and has a Short-Range dependency.
Variable 'returnVal' used at line 40 is defined at line 31 and has a Short-Range dependency.
Variable 'returnVal' used at line 41 is defined at line 40 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 6, 'If Condition': 1, 'If Body': 1} | {'Variable Short-Range': 8, 'Function Medium-Range': 2} |
completion_java | DoubleVectorTester | 35 | 36 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string'] | [' if (i != 0)', ' returnVal = returnVal + ", ";'] | [' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'If Condition', 'usage_line': 35}, {'reason_category': 'Loop Body', 'usage_line': 35}, {'reason_category': 'If Body', 'usage_line': 36}, {'reason_category': 'Loop Body', 'usage_line': 36}] | Variable 'i' used at line 35 is defined at line 32 and has a Short-Range dependency.
Variable 'returnVal' used at line 36 is defined at line 31 and has a Short-Range dependency. | {'If Condition': 1, 'Loop Body': 2, 'If Body': 1} | {'Variable Short-Range': 2} |
completion_java | DoubleVectorTester | 38 | 38 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string'] | [' returnVal = returnVal + curItem.toString (); '] | [' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 38}] | Variable 'returnVal' used at line 38 is defined at line 36 and has a Short-Range dependency.
Variable 'curItem' used at line 38 is defined at line 33 and has a Short-Range dependency. | {'Loop Body': 1} | {'Variable Short-Range': 2} |
completion_java | DoubleVectorTester | 51 | 51 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {'] | [' return Math.round (getItem (whichOne)); '] | [' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [] | Library 'Math' used at line 51 is defined at line 3 and has a Long-Range dependency.
Function 'getItem' used at line 51 is defined at line 18 and has a Long-Range dependency.
Variable 'whichOne' used at line 51 is defined at line 50 and has a Short-Range dependency. | {} | {'Library Long-Range': 1, 'Function Long-Range': 1, 'Variable Short-Range': 1} |
completion_java | DoubleVectorTester | 219 | 221 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array'] | [' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }'] | [' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 219}, {'reason_category': 'Loop Body', 'usage_line': 220}, {'reason_category': 'Loop Body', 'usage_line': 221}] | Variable 'i' used at line 219 is defined at line 219 and has a Short-Range dependency.
Variable 'len' used at line 219 is defined at line 213 and has a Short-Range dependency.
Global_Variable 'myData' used at line 220 is defined at line 216 and has a Short-Range dependency.
Variable 'i' used at line 220 is defined at line 219 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 2} | {'Variable Short-Range': 3, 'Global_Variable Short-Range': 1} |
completion_java | DoubleVectorTester | 224 | 224 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value'] | [' baselineData = initialValue;'] | [' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [] | Variable 'initialValue' used at line 224 is defined at line 213 and has a Medium-Range dependency.
Global_Variable 'baselineData' used at line 224 is defined at line 204 and has a Medium-Range dependency. | {} | {'Variable Medium-Range': 1, 'Global_Variable Medium-Range': 1} |
completion_java | DoubleVectorTester | 237 | 237 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {'] | [' returnVal += Math.abs (myData[i] + baselineData);'] | [' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 237}] | Library 'Math' used at line 237 is defined at line 3 and has a Long-Range dependency.
Global_Variable 'myData' used at line 237 is defined at line 200 and has a Long-Range dependency.
Variable 'i' used at line 237 is defined at line 236 and has a Short-Range dependency.
Global_Variable 'baselineData' used at line 237 is defined at line 204 and has a Long-Range dependency.
Variable 'returnVal' used at line 237 is defined at line 235 and has a Short-Range dependency. | {'Loop Body': 1} | {'Library Long-Range': 1, 'Global_Variable Long-Range': 2, 'Variable Short-Range': 2} |
completion_java | DoubleVectorTester | 245 | 247 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {'] | [' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;'] | [' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 245}, {'reason_category': 'Loop Body', 'usage_line': 246}, {'reason_category': 'Loop Body', 'usage_line': 247}] | Global_Variable 'myData' used at line 245 is defined at line 200 and has a Long-Range dependency.
Variable 'i' used at line 245 is defined at line 244 and has a Short-Range dependency.
Global_Variable 'baselineData' used at line 246 is defined at line 204 and has a Long-Range dependency.
Variable 'trueVal' used at line 246 is defined at line 245 and has a Short-Range dependency.
Variable 'trueVal' used at line 247 is defined at line 246 and has a Short-Range dependency.
Variable 'total' used at line 247 is defined at line 243 and has a Short-Range dependency.
Global_Variable 'baselineData' used at line 247 is defined at line 204 and has a Long-Range dependency.
Global_Variable 'myData' used at line 247 is defined at line 200 and has a Long-Range dependency.
Variable 'i' used at line 247 is defined at line 244 and has a Short-Range dependency. | {'Loop Body': 3} | {'Global_Variable Long-Range': 4, 'Variable Short-Range': 5} |
completion_java | DoubleVectorTester | 249 | 249 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }'] | [' baselineData /= total;'] | [' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [] | Variable 'total' used at line 249 is defined at line 243 and has a Short-Range dependency.
Global_Variable 'baselineData' used at line 249 is defined at line 204 and has a Long-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Long-Range': 1} |
completion_java | DoubleVectorTester | 260 | 263 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {'] | [' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }'] | [' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 260}, {'reason_category': 'Loop Body', 'usage_line': 261}, {'reason_category': 'Loop Body', 'usage_line': 262}, {'reason_category': 'Loop Body', 'usage_line': 263}] | Variable 'addToThisOne' used at line 260 is defined at line 252 and has a Short-Range dependency.
Variable 'i' used at line 260 is defined at line 259 and has a Short-Range dependency.
Global_Variable 'myData' used at line 261 is defined at line 200 and has a Long-Range dependency.
Variable 'i' used at line 261 is defined at line 259 and has a Short-Range dependency.
Variable 'value' used at line 261 is defined at line 260 and has a Short-Range dependency.
Variable 'addToThisOne' used at line 262 is defined at line 252 and has a Short-Range dependency.
Variable 'i' used at line 262 is defined at line 259 and has a Short-Range dependency.
Variable 'value' used at line 262 is defined at line 261 and has a Short-Range dependency. | {'Loop Body': 4} | {'Variable Short-Range': 7, 'Global_Variable Long-Range': 1} |
completion_java | DoubleVectorTester | 273 | 273 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' '] | [' return myData[whichOne] + baselineData;'] | [' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [] | Global_Variable 'myData' used at line 273 is defined at line 200 and has a Long-Range dependency.
Variable 'whichOne' used at line 273 is defined at line 267 and has a Short-Range dependency.
Global_Variable 'baselineData' used at line 273 is defined at line 204 and has a Long-Range dependency. | {} | {'Global_Variable Long-Range': 2, 'Variable Short-Range': 1} |
completion_java | DoubleVectorTester | 279 | 279 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {'] | [' throw new OutOfBoundsException ("index too large in setItem");'] | [' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 279}] | Class 'OutOfBoundsException' used at line 279 is defined at line 184 and has a Long-Range dependency. | {'If Body': 1} | {'Class Long-Range': 1} |
completion_java | DoubleVectorTester | 282 | 282 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', ''] | [' myData[whichOne] = setToMe - baselineData;'] | [' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [] | Variable 'setToMe' used at line 282 is defined at line 276 and has a Short-Range dependency.
Global_Variable 'baselineData' used at line 282 is defined at line 204 and has a Long-Range dependency.
Global_Variable 'myData' used at line 282 is defined at line 200 and has a Long-Range dependency.
Variable 'whichOne' used at line 282 is defined at line 276 and has a Short-Range dependency. | {} | {'Variable Short-Range': 2, 'Global_Variable Long-Range': 2} |
completion_java | DoubleVectorTester | 286 | 286 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {'] | [' baselineData += addMe;'] | [' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [] | Variable 'addMe' used at line 286 is defined at line 285 and has a Short-Range dependency.
Global_Variable 'baselineData' used at line 286 is defined at line 204 and has a Long-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Long-Range': 1} |
completion_java | DoubleVectorTester | 329 | 330 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();'] | [' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);'] | [' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 329}, {'reason_category': 'Loop Body', 'usage_line': 330}] | Variable 'value' used at line 329 is defined at line 327 and has a Short-Range dependency.
Global_Variable 'baselineValue' used at line 329 is defined at line 304 and has a Medium-Range dependency.
Variable 'total' used at line 329 is defined at line 325 and has a Short-Range dependency.
Variable 'newValue' used at line 330 is defined at line 329 and has a Short-Range dependency.
Global_Variable 'baselineValue' used at line 330 is defined at line 304 and has a Medium-Range dependency.
Variable 'total' used at line 330 is defined at line 325 and has a Short-Range dependency.
Variable 'value' used at line 330 is defined at line 327 and has a Short-Range dependency. | {'Loop Body': 2} | {'Variable Short-Range': 5, 'Global_Variable Medium-Range': 2} |
completion_java | DoubleVectorTester | 334 | 334 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' '] | [' baselineValue /= total;'] | [' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }', ' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [] | Variable 'total' used at line 334 is defined at line 325 and has a Short-Range dependency.
Global_Variable 'baselineValue' used at line 334 is defined at line 304 and has a Medium-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Medium-Range': 1} |
completion_java | DoubleVectorTester | 343 | 345 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.lang.Math;', 'import java.util.*;', '', '/**', ' * This abstract class serves as the basis from which all of the DoubleVector', ' * implementations should be extended. Most of the methods are abstract, but', ' * this class does provide implementations of a couple of the DoubleVector methods.', ' * See the DoubleVector interface for a description of each of the methods.', ' */', 'abstract class ADoubleVector implements IDoubleVector {', ' ', ' /** ', ' * These methods are all abstract!', ' */', ' public abstract void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException;', ' public abstract double getItem (int whichOne) throws OutOfBoundsException;', ' public abstract void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', ' public abstract int getLength ();', ' public abstract void addToAll (double addMe);', ' public abstract double l1Norm ();', ' public abstract void normalize ();', ' ', ' /* These two methods re the only ones provided by the AbstractDoubleVector.', ' * toString method constructs a string representation of a DoubleVector by adding each item to the string with < and > at the beginning and end of the string.', ' */', ' public String toString () {', ' ', ' try {', ' String returnVal = new String ("<");', ' for (int i = 0; i < getLength (); i++) {', ' Double curItem = getItem (i);', ' // If the current index is not 0, add a comma and a space to the string', ' if (i != 0)', ' returnVal = returnVal + ", ";', ' // Add the string representation of the current item to the string', ' returnVal = returnVal + curItem.toString (); ', ' }', ' returnVal = returnVal + ">";', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' ', ' System.out.println ("This is strange. getLength() seems to be incorrect?");', ' return new String ("<>");', ' }', ' }', ' ', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException {', ' return Math.round (getItem (whichOne)); ', ' }', '}', '', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds the contents of this double vector to the other one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addToHim the double vector to be added to', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the absolute value of the sum of all of the items in the vector to be one, by ', ' * dividing each item by the absolute value of the total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', '', '/**', ' * This is thrown when someone tries to access an element in a DoubleVector that is beyond the end of ', ' * the vector.', ' */', 'class OutOfBoundsException extends Exception {', ' static final long serialVersionUID = 2304934980L;', '', ' public OutOfBoundsException(String message) {', ' super(message);', ' }', '}', '', '', '/** ', ' * Implementaiton of the DoubleVector interface that really just wraps up', ' * an array and implements the DoubleVector operations on top of the array.', ' */', 'class DenseDoubleVector extends ADoubleVector {', ' ', ' // holds the data', ' private double [] myData;', ' ', ' // remembers what the the baseline is; that is, every value actually stored in', ' // myData is a delta from this', ' private double baselineData;', ' ', ' /**', ' * This creates a DenseDoubleVector having the specified length; all of the entries in the', ' * double vector are set to have the specified initial value.', ' * ', ' * @param len The length of the new double vector we are creating.', ' * @param initialValue The default value written into all entries in the vector', ' */', ' public DenseDoubleVector (int len, double initialValue) {', ' ', ' // allocate the space', ' myData = new double[len];', ' ', ' // initialize the array', ' for (int i = 0; i < len; i++) {', ' myData[i] = 0.0;', ' }', ' ', ' // the baseline data is set to the initial value', ' baselineData = initialValue;', ' }', ' ', ' public int getLength () {', ' return myData.length;', ' }', ' ', ' /*', ' * Method that calculates the L1 norm of the DoubleVector. ', ' */', ' public double l1Norm () {', ' double returnVal = 0.0;', ' for (int i = 0; i < myData.length; i++) {', ' returnVal += Math.abs (myData[i] + baselineData);', ' }', ' return returnVal;', ' }', ' ', ' public void normalize () {', ' double total = l1Norm ();', ' for (int i = 0; i < myData.length; i++) {', ' double trueVal = myData[i];', ' trueVal += baselineData;', ' myData[i] = trueVal / total - baselineData / total;', ' }', ' baselineData /= total;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToThisOne) throws OutOfBoundsException {', '', ' if (getLength() != addToThisOne.getLength()) {', ' throw new OutOfBoundsException("vectors are different sizes");', ' }', ' ', ' // easy... just do the element-by-element addition', ' for (int i = 0; i < myData.length; i++) {', ' double value = addToThisOne.getItem (i);', ' value += myData[i];', ' addToThisOne.setItem (i, value);', ' }', ' addToThisOne.addToAll (baselineData);', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) { ', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' return myData[whichOne] + baselineData;', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', ' ', ' if (whichOne >= myData.length) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' } ', '', ' myData[whichOne] = setToMe - baselineData;', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineData += addMe;', ' }', ' ', '}', '', '', '/**', ' * Implementation of the DoubleVector that uses a sparse representation (that is,', ' * not all of the entries in the vector are explicitly represented). All non-default', ' * entires in the vector are stored in a HashMap.', ' */', 'class SparseDoubleVector extends ADoubleVector {', ' ', ' // this stores all of the non-default entries in the sparse vector', ' private ISparseArray<Double> nonEmptyEntries;', ' ', ' // everyone in the vector has this value as a baseline; the actual entries ', ' // that are stored are deltas from this', ' private double baselineValue;', ' ', ' // how many entries there are in the vector', ' private int myLength;', ' ', ' /**', ' * Creates a new DoubleVector of the specified length with the spefified initial value.', ' * Note that since this uses a sparse represenation, putting the inital value in every', ' * entry is efficient and uses no memory.', ' * ', ' * @param len the length of the vector we are creating', ' * @param initalValue the initial value to "write" in all of the vector entries', ' */', ' public SparseDoubleVector (int len, double initialValue) {', ' myLength = len;', ' baselineValue = initialValue;', ' nonEmptyEntries = new SparseArray<Double>();', ' }', ' ', ' public void normalize () {', ' ', ' double total = l1Norm ();', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' Double value = el.getData();', ' int position = el.getIndex();', ' double newValue = (value + baselineValue) / total;', ' value = newValue - (baselineValue / total);', ' nonEmptyEntries.put(position, value);', ' }', ' ', ' baselineValue /= total;', ' }', ' ', ' public double l1Norm () {', ' ', ' // iterate through all of the values', ' double returnVal = 0.0;', ' int nonEmptyEls = 0;', ' for (IIndexedData<Double> el : nonEmptyEntries) {'] | [' returnVal += Math.abs (el.getData() + baselineValue);', ' nonEmptyEls += 1;', ' }'] | [' ', ' // and add in the total for everyone who is not explicitly represented', ' returnVal += Math.abs ((myLength - nonEmptyEls) * baselineValue);', ' return returnVal;', ' }', ' ', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException {', ' // make sure that the two vectors have the same length', ' if (getLength() != addToHim.getLength ()) {', ' throw new OutOfBoundsException ("unequal lengths in addMyselfToHim");', ' }', ' ', ' // add every non-default value to the other guy', ' for (IIndexedData<Double> el : nonEmptyEntries) {', ' double myVal = el.getData();', ' int curIndex = el.getIndex();', ' myVal += addToHim.getItem (curIndex);', ' addToHim.setItem (curIndex, myVal);', ' }', ' ', ' // and add my baseline in', ' addToHim.addToAll (baselineValue);', ' }', ' ', ' public void addToAll (double addMe) {', ' baselineValue += addMe;', ' }', ' ', ' public double getItem (int whichOne) throws OutOfBoundsException {', ' ', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in getItem");', ' }', ' ', ' // now, look the thing up', ' Double myVal = nonEmptyEntries.get (whichOne);', ' if (myVal == null) {', ' return baselineValue;', ' } else {', ' return myVal + baselineValue;', ' }', ' }', ' ', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException {', '', ' // make sure we are not out of bounds', ' if (whichOne >= myLength || whichOne < 0) {', ' throw new OutOfBoundsException ("index too large in setItem");', ' }', ' ', ' // try to put the value in', ' nonEmptyEntries.put (whichOne, setToMe - baselineValue);', ' }', ' ', ' public int getLength () {', ' return myLength;', ' }', '}', '', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class DoubleVectorTester extends TestCase {', ' ', ' /**', ' * In this part of the code we have a number of helper functions', ' * that will be used by the actual test functions to test specific', ' * functionality.', ' */', ' ', ' /**', ' * This is used all over the place to check if an observed value is', ' * close enough to an expected double value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) {', ' if (!(observed >= goal - 1e-8 - Math.abs (goal * 1e-8) && ', ' observed <= goal + 1e-8 + Math.abs (goal * 1e-8)))', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal);', ' else', ' fail ("Got " + observed + ", expected " + goal);', ' }', ' ', ' /** ', ' * This adds a bunch of data into testMe, then checks (and returns)', ' * the l1norm', ' */', ' private double l1NormTester (IDoubleVector testMe, double init) {', ' ', ' // This will by used to scatter data randomly', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // pick a bunch of random locations and repeatedly add an integer in', ' double total = 0.0;', ' int pos = 0;', ' while (pos < testMe.getLength ()) {', ' ', " // there's a 20% chance we keep going", ' if (rng.nextDouble () > .2) {', ' pos++;', ' continue;', ' }', ' ', ' // otherwise, add a value in', ' try {', ' double current = testMe.getItem (pos);', ' testMe.setItem (pos, current + pos);', ' total += pos;', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + pos + " not expecting one!\\n");', ' }', ' }', ' ', ' // now test the l1 norm', ' double expected = testMe.getLength () * init + total;', ' checkCloseEnough (testMe.l1Norm (), expected, -1);', ' return expected;', ' }', ' ', ' /**', ' * This does a large number of setItems to an array of double vectors,', ' * and then makes sure that all of the set values are still there', ' */', ' private void doLotsOfSets (IDoubleVector [] allMyVectors, double init) {', ' ', ' int numVecs = allMyVectors.length;', ' ', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' try {', ' allMyVectors[whichOne].setItem (i, 1.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' ', ' // now check all of that data', ' // put data in exectly one array in each dimension', ' for (int i = 0; i < allMyVectors[0].getLength (); i++) {', ' ', ' int whichOne = i % numVecs;', ' for (int j = 0; j < numVecs; j++) {', ' try {', ' if (whichOne == j) {', ' checkCloseEnough (allMyVectors[j].getItem (i), 1.345, j);', ' } else {', ' checkCloseEnough (allMyVectors[j].getItem (i), init, j); ', ' } ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' }', ' ', ' /**', ' * This sets only the first value in a double vector, and then checks', ' * to see if only the first vlaue has an updated value.', ' */', ' private void trivialGetAndSet (IDoubleVector testMe, double init) {', ' try {', ' ', ' // set the first item', ' testMe.setItem (0, 11.345);', ' ', ' // now retrieve and test everything except for the first one', ' for (int i = 1; i < testMe.getLength (); i++) {', ' checkCloseEnough (testMe.getItem (i), init, i);', ' }', ' ', ' // and check the first one', ' checkCloseEnough (testMe.getItem (0), 11.345, 0);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' }', ' }', ' ', ' /**', ' * This uses the l1NormTester to set a bunch of stuff in the input', ' * DoubleVector. It then normalizes it, and checks to see that things', ' * have been normalized correctly.', ' */', ' private void normalizeTester (IDoubleVector myVec, double init) {', '', " // get the L1 norm, and make sure it's correct", ' double result = l1NormTester (myVec, init);', ' ', ' try {', ' // now get an array of ratios', ' double [] ratios = new double[myVec.getLength ()];', ' for (int i = 0; i < myVec.getLength (); i++) {', ' ratios[i] = myVec.getItem (i) / result;', ' }', ' ', ' // and do the normalization on myVec', ' myVec.normalize ();', ' ', ' // now check it if it is close enough to an expected double value', ' for (int i = 0; i < myVec.getLength (); i++) {', ' checkCloseEnough (ratios[i], myVec.getItem (i), i);', ' } ', ' ', ' // and make sure the length is one', ' checkCloseEnough (myVec.l1Norm (), 1.0, -1);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get... not expecting one!\\n");', ' } ', ' }', ' ', ' /**', ' * Here we have the various test functions, organized in increasing order of difficulty.', ' * The code for most of them is quite short, and self-explanatory.', ' */', ' ', ' public void testSingleDenseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleSparseSetSize1 () {', ' int vecLen = 1;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 345.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testSingleDenseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 245.67);', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' //initialValue: 145.67', ' public void testSingleSparseSetSize1000 () {', ' int vecLen = 1000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' trivialGetAndSet (myVec, 145.67);', ' assertEquals (myVec.getLength (), vecLen);', ' } ', ' ', ' public void testLotsOfDenseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSets () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfDenseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new DenseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new DenseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (2.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, 2.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testLotsOfSparseSetsWithAddToAll () {', ' ', ' int numVecs = 100;', ' int vecLen = 10000;', ' IDoubleVector [] allMyVectors = new SparseDoubleVector [numVecs];', ' for (int i = 0; i < numVecs; i++) {', ' allMyVectors[i] = new SparseDoubleVector (vecLen, 0.0);', ' allMyVectors[i].addToAll (-12.345);', ' }', ' ', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' doLotsOfSets (allMyVectors, -12.345);', ' assertEquals (allMyVectors[0].getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormDenseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseShort () {', ' int vecLen = 10;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testL1NormSparseLong () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 45.67);', ' assertEquals (myVec.getLength (), vecLen);', ' l1NormTester (myVec, 45.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testRounding () {', ' ', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' // create the vectors', ' int vecLen = 100000;', ' IDoubleVector myVec1 = new DenseDoubleVector (vecLen, 55.0);', ' IDoubleVector myVec2 = new SparseDoubleVector (vecLen, 55.0);', ' ', ' // put values with random additional precision in', ' for (int i = 0; i < vecLen; i++) {', ' double valToPut = i + (0.5 - rng.nextDouble ()) * .9;', ' try {', ' myVec1.setItem (i, valToPut);', ' myVec2.setItem (i, valToPut);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' ', ' // and extract those values', ' for (int i = 0; i < vecLen; i++) {', ' try {', ' checkCloseEnough (myVec1.getRoundedItem (i), i, i);', ' checkCloseEnough (myVec2.getRoundedItem (i), i, i);', ' } catch (OutOfBoundsException e) {', ' fail ("not expecting an out-of-bounds here");', ' }', ' }', ' } ', ' ', ' public void testOutOfBounds () {', ' ', ' int vecLen = 1000;', ' SparseDoubleVector vec1 = new SparseDoubleVector (vecLen, 0.0);', ' SparseDoubleVector vec2 = new SparseDoubleVector (vecLen + 1, 0.0);', ' ', ' try {', ' vec1.getItem (-1);', ' fail ("Missed bad getItem #1");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.getItem (vecLen);', ' fail ("Missed bad getItem #2");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (-1, 0.0);', ' fail ("Missed bad setItem #3");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.setItem (vecLen, 0.0);', ' fail ("Missed bad setItem #4");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (-1);', ' fail ("Missed bad getItem #5");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.getItem (vecLen + 1);', ' fail ("Missed bad getItem #6");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (-1, 0.0);', ' fail ("Missed bad setItem #7");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.setItem (vecLen + 1, 0.0);', ' fail ("Missed bad setItem #8");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec1.addMyselfToHim (vec2);', ' fail ("Missed bad add #9");', ' } catch (OutOfBoundsException e) {}', ' ', ' try {', ' vec2.addMyselfToHim (vec1);', ' fail ("Missed bad add #10");', ' } catch (OutOfBoundsException e) {}', ' }', ' ', ' /**', ' * This test creates 100 sparse double vectors, and puts a bunch of data into them', ' * pseudo-randomly. Then it adds each of them, in turn, into a single dense double', ' * vector, which is then tested to see if everything adds up.', ' */', ' public void testLotsOfAdds() {', ' ', ' // This will by used to scatter data randomly into various sparse arrays', " // Note we don't want test cases to share the random number generator, since this", ' // will create dependencies among them', ' Random rng = new Random (12345);', ' ', ' IDoubleVector [] allMyVectors = new IDoubleVector [100];', ' for (int i = 0; i < 100; i++) {', ' allMyVectors[i] = new SparseDoubleVector (10000, i * 2.345);', ' }', ' ', ' // put data in each dimension', ' for (int i = 0; i < 10000; i++) {', ' ', ' // randomly choose 20 dims to put data into', ' for (int j = 0; j < 20; j++) {', ' int whichOne = (int) Math.floor (100.0 * rng.nextDouble ());', ' try {', ' allMyVectors[whichOne].setItem (i, allMyVectors[whichOne].getItem (i) + i * 2.345);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on set/get pos " + whichOne + " not expecting one!\\n");', ' }', ' }', ' }', ' ', ' // now, add the data up', ' DenseDoubleVector result = new DenseDoubleVector (10000, 0.0);', ' for (int i = 0; i < 100; i++) {', ' try {', ' allMyVectors[i].addMyselfToHim (result);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception adding two vectors, not expecting one!");', ' }', ' }', ' ', ' // and check the final result', ' for (int i = 0; i < 10000; i++) {', ' double expectedValue = (i * 20.0 + 100.0 * 99.0 / 2.0) * 2.345;', ' try {', ' checkCloseEnough (result.getItem (i), expectedValue, i);', ' } catch (OutOfBoundsException e) {', ' fail ("Got an out of bounds exception on getItem, not expecting one!");', ' }', ' }', ' }', ' ', ' public void testNormalizeDense () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new DenseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', ' ', ' public void testNormalizeSparse () {', ' int vecLen = 100000;', ' IDoubleVector myVec = new SparseDoubleVector (vecLen, 55.67);', ' assertEquals (myVec.getLength (), vecLen);', ' normalizeTester (myVec, 55.67); ', ' assertEquals (myVec.getLength (), vecLen);', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 343}, {'reason_category': 'Loop Body', 'usage_line': 344}, {'reason_category': 'Loop Body', 'usage_line': 345}] | Library 'Math' used at line 343 is defined at line 3 and has a Long-Range dependency.
Variable 'el' used at line 343 is defined at line 342 and has a Short-Range dependency.
Global_Variable 'baselineValue' used at line 343 is defined at line 304 and has a Long-Range dependency.
Variable 'returnVal' used at line 343 is defined at line 340 and has a Short-Range dependency.
Variable 'nonEmptyEls' used at line 344 is defined at line 341 and has a Short-Range dependency. | {'Loop Body': 3} | {'Library Long-Range': 1, 'Variable Short-Range': 3, 'Global_Variable Long-Range': 1} |