Skip to content

Commit c069a3d

Browse files
author
phishman3579
committed
Implemented clear() in collections and updated the Map put() methods to return null unless a key already exists.
git-svn-id: https://java-algorithms-implementation.googlecode.com/svn/trunk@440 032fbc0f-8cab-eb90-e552-f08422b9a96a
1 parent b2da2cc commit c069a3d

23 files changed

+308
-63
lines changed

src/com/jwetherell/algorithms/DataStructures.java

+25-29
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ public class DataStructures {
7070

7171
private static final int NUMBER_OF_TESTS = 3;
7272
private static final Random RANDOM = new Random();
73-
private static final int ARRAY_SIZE = 100000;
73+
private static final int ARRAY_SIZE = 1000;
7474
private static final int RANDOM_SIZE = 1000 * ARRAY_SIZE;
7575
private static final Integer INVALID = RANDOM_SIZE + 10;
7676
private static final DecimalFormat FORMAT = new DecimalFormat("0.##");
@@ -82,21 +82,13 @@ public class DataStructures {
8282
private static int debug = 1; // Debug level. 0=None, 1=Time and Memory (if enabled), 2=Time, Memory, data structure debug
8383
private static boolean debugTime = true; // How much time to: add all, remove all, add all items in reverse order, remove all
8484
private static boolean debugMemory = true; // How much memory is used by the data structure
85-
private static boolean validateStructure = false; // Is the data structure valid (passed invariants) and proper size
86-
private static boolean validateContents = false; // Was the item added/removed really added/removed from the structure
87-
private static boolean validateIterator = false; // Does the iterator(s) work
85+
private static boolean validateStructure = true; // Is the data structure valid (passed invariants) and proper size
86+
private static boolean validateContents = true; // Was the item added/removed really added/removed from the structure
87+
private static boolean validateIterator = true; // Does the iterator(s) work
8888

8989
private static final int TESTS = 38; // Max number of dynamic data structures to test
9090
private static final String[] testNames = new String[TESTS]; // Array to hold the test names
9191
private static final long[][] testResults = new long[TESTS][]; // Array to hold the test results
92-
private static final long[] minResults = new long[TESTS]; // Array to hold the min results
93-
private static final long[] maxResults = new long[TESTS]; // Array to hold the max results
94-
static {
95-
for (int i=0; i<TESTS; i++) {
96-
minResults[i] = Long.MAX_VALUE;
97-
maxResults[i] = Long.MIN_VALUE;
98-
}
99-
}
10092
private static int testIndex = 0; // Index into the tests
10193
private static int testNumber = 0; // Number of aggregate tests which have been run
10294

@@ -118,10 +110,7 @@ public static void main(String[] args) {
118110
else System.err.println("Tests finished. Detected a failure.");
119111
}
120112

121-
private static boolean runTests() {
122-
testIndex = 0;
123-
testNumber++;
124-
113+
private static void generateData() {
125114
System.out.println("Generating data.");
126115
StringBuilder builder = new StringBuilder();
127116
builder.append("Array=");
@@ -153,6 +142,13 @@ private static boolean runTests() {
153142
Arrays.sort(sorted);
154143

155144
System.out.println("Generated data.");
145+
}
146+
147+
private static boolean runTests() {
148+
testIndex = 0;
149+
testNumber++;
150+
151+
generateData();
156152

157153
boolean passed = true;
158154

@@ -567,8 +563,7 @@ private static boolean testGraph() {
567563
if (debug > 1) System.out.println(getPathMapString(start, map1));
568564

569565
Graph.Vertex<Integer> end = v5;
570-
if (debug > 1) System.out.println("Dijstra's shortest path of the undirected graph from " + start.getValue() + " to "
571-
+ end.getValue());
566+
if (debug > 1) System.out.println("Dijstra's shortest path of the undirected graph from " + start.getValue() + " to " + end.getValue());
572567
Graph.CostPathPair<Integer> pair1 = Dijkstra.getShortestPath(undirected, start, end);
573568
if (debug > 1) {
574569
if (pair1 != null) System.out.println(pair1.toString());
@@ -1281,7 +1276,7 @@ private static boolean testQuadTree() {
12811276
}
12821277
afterInsert = System.nanoTime();
12831278
insertTime = afterInsert - beforeInsert;
1284-
System.out.println("PointRegionQuadTree insertTime="+insertTime);
1279+
System.out.println("PointRegionQuadTree insertTime="+insertTime/100000d+" ms");
12851280
}
12861281
afterMemory = DataStructures.getMemoryUse();
12871282
treeMemory = afterMemory - beforeMemory;
@@ -1303,15 +1298,15 @@ private static boolean testQuadTree() {
13031298
}
13041299
afterQuery = System.nanoTime();
13051300
queryTime = afterQuery - beforeQuery;
1306-
System.out.println("PointRegionQuadTree queryTime="+queryTime);
1301+
System.out.println("PointRegionQuadTree queryTime="+queryTime/100000d+" ms");
13071302
}
13081303

13091304
// Result set should not contain duplicates
13101305
beforeTreeQuery = System.nanoTime();
13111306
java.util.List<QuadTree.XYPoint> result = tree.queryRange(0, 0, size, size);
13121307
afterTreeQuery = System.nanoTime();
13131308
treeQuery = afterTreeQuery - beforeTreeQuery;
1314-
System.out.println("PointRegionQuadTree wholeTreeQuery="+treeQuery);
1309+
System.out.println("PointRegionQuadTree wholeTreeQuery="+treeQuery/100000d+" ms");
13151310
Collections.sort(result);
13161311
QuadTree.XYPoint prev = null;
13171312
for (QuadTree.XYPoint p : result) {
@@ -1329,7 +1324,7 @@ private static boolean testQuadTree() {
13291324
}
13301325
afterRemove = System.nanoTime();
13311326
removeTime = afterRemove - beforeRemove;
1332-
System.out.println("PointRegionQuadTree removeTime="+removeTime);
1327+
System.out.println("PointRegionQuadTree removeTime="+removeTime/100000d+" ms");
13331328
}
13341329
}
13351330

@@ -1343,7 +1338,7 @@ private static boolean testQuadTree() {
13431338
}
13441339
afterInsert = System.nanoTime();
13451340
insertTime = afterInsert - beforeInsert;
1346-
System.out.println("MxCifQuadTree insertTime="+insertTime);
1341+
System.out.println("MxCifQuadTree insertTime="+insertTime/100000d+" ms");
13471342
}
13481343
afterMemory = DataStructures.getMemoryUse();
13491344
treeMemory = afterMemory - beforeMemory;
@@ -1364,15 +1359,15 @@ private static boolean testQuadTree() {
13641359
}
13651360
afterQuery = System.nanoTime();
13661361
queryTime = afterQuery - beforeQuery;
1367-
System.out.println("MxCifQuadTree queryTime="+queryTime);
1362+
System.out.println("MxCifQuadTree queryTime="+queryTime/100000d+" ms");
13681363
}
13691364

13701365
// Result set should not contain duplicates
13711366
beforeTreeQuery = System.nanoTime();
13721367
java.util.List<QuadTree.AxisAlignedBoundingBox> result = tree.queryRange(0, 0, size, size);
13731368
afterTreeQuery = System.nanoTime();
13741369
treeQuery = afterTreeQuery - beforeTreeQuery;
1375-
System.out.println("MxCifQuadTree wholeTreeQuery="+treeQuery);
1370+
System.out.println("MxCifQuadTree wholeTreeQuery="+treeQuery/100000d+" ms");
13761371
Collections.sort(result);
13771372
QuadTree.AxisAlignedBoundingBox prev = null;
13781373
for (QuadTree.AxisAlignedBoundingBox p : result) {
@@ -1392,7 +1387,7 @@ private static boolean testQuadTree() {
13921387
}
13931388
afterRemove = System.nanoTime();
13941389
removeTime = afterRemove - beforeRemove;
1395-
System.out.println("MxCifQuadTree removeTime="+removeTime);
1390+
System.out.println("MxCifQuadTree removeTime="+removeTime/100000d+" ms");
13961391
}
13971392
}
13981393

@@ -1815,7 +1810,7 @@ private static <K,V> boolean testMap(IMap<K,V> map, Type keyType, String name) {
18151810
handleError(map);
18161811
return false;
18171812
}
1818-
if (validateContents && (added==null || !map.contains(k))) {
1813+
if (validateContents && (added!=null || !map.contains(k))) {
18191814
System.err.println(name+" YIKES!! " + item + " doesn't exists.");
18201815
handleError(map);
18211816
return false;
@@ -1877,7 +1872,7 @@ private static <K,V> boolean testMap(IMap<K,V> map, Type keyType, String name) {
18771872
handleError(map);
18781873
return false;
18791874
}
1880-
if (validateContents && (added==null || !map.contains(k))) {
1875+
if (validateContents && (added!=null || !map.contains(k))) {
18811876
System.err.println(name+" YIKES!! " + item + " doesn't exists.");
18821877
handleError(map);
18831878
return false;
@@ -1920,7 +1915,7 @@ private static <K,V> boolean testMap(IMap<K,V> map, Type keyType, String name) {
19201915
handleError(map);
19211916
return false;
19221917
}
1923-
if (validateContents && (added==null || !map.contains(k))) {
1918+
if (validateContents && (added!=null || !map.contains(k))) {
19241919
System.err.println(name+" YIKES!! " + item + " doesn't exists.");
19251920
handleError(map);
19261921
return false;
@@ -4085,6 +4080,7 @@ private static final long getMemoryUse() {
40854080
private static final void putOutTheGarbage() {
40864081
collectGarbage();
40874082
collectGarbage();
4083+
collectGarbage();
40884084
}
40894085

40904086
private static final long fSLEEP_INTERVAL = 100;

src/com/jwetherell/algorithms/data_structures/BTree.java

+9
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,15 @@ private T removeGreatestValue(Node<T> node) {
222222
return value;
223223
}
224224

225+
/**
226+
* {@inheritDoc}
227+
*/
228+
@Override
229+
public void clear() {
230+
root = null;
231+
size = 0;
232+
}
233+
225234
/**
226235
* {@inheritDoc}
227236
*/

src/com/jwetherell/algorithms/data_structures/BinaryHeap.java

+17
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,14 @@ private T remove(int index) {
177177
return t;
178178
}
179179

180+
/**
181+
* {@inheritDoc}
182+
*/
183+
@Override
184+
public void clear() {
185+
size = 0;
186+
}
187+
180188
/**
181189
* {@inheritDoc}
182190
*/
@@ -592,6 +600,15 @@ private Node<T> getNode(Node<T> startingNode, T value) {
592600
return result;
593601
}
594602

603+
/**
604+
* {@inheritDoc}
605+
*/
606+
@Override
607+
public void clear() {
608+
root = null;
609+
size = 0;
610+
}
611+
595612
/**
596613
* {@inheritDoc}
597614
*/

src/com/jwetherell/algorithms/data_structures/BinarySearchTree.java

+9
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,15 @@ protected void replaceNodeWithNode(Node<T> nodeToRemoved, Node<T> replacementNod
416416
size--;
417417
}
418418

419+
/**
420+
* {@inheritDoc}
421+
*/
422+
@Override
423+
public void clear() {
424+
root = null;
425+
size = 0;
426+
}
427+
419428
/**
420429
* {@inheritDoc}
421430
*/

src/com/jwetherell/algorithms/data_structures/HashArrayMappedTrie.java

+27-10
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ public class HashArrayMappedTrie<K, V> implements IMap<K,V> {
2222
private static final byte MAX_BITS = 32;
2323
private static final byte BITS = 5;
2424
private static final byte MAX_DEPTH = MAX_BITS/BITS; // 6
25+
private static final int MASK = (int)Math.pow(2, BITS)-1;
2526

2627
private Node root = null;
2728
private int size = 0;
@@ -47,7 +48,7 @@ private static final String toBinaryString(int value) {
4748
* e.g. BITS=5 height=1 value==266 big-endian=100001010 (shifts height*BITS off the right) return=1000 (8 in decimal)
4849
*/
4950
private static final int getPosition(int height, int value) {
50-
return (value >>> height*BITS) & 0x01f;
51+
return (value >>> height*BITS) & MASK;
5152
}
5253

5354
private V put(ArrayNode parent, Node node, byte height, int key, V value) {
@@ -77,7 +78,7 @@ private V put(ArrayNode parent, Node node, byte height, int key, V value) {
7778
newParent.addChild(oldParentPosition, oldParent);
7879
oldParent.parent = newParent;
7980
newParent.addChild(childPosition, new KeyValueNode<V>(newParent, key, value));
80-
return value;
81+
return null;
8182
}
8283
while (oldParentPosition == childPosition) {
8384
// Handle the case when the new children map to same position.
@@ -101,15 +102,15 @@ private V put(ArrayNode parent, Node node, byte height, int key, V value) {
101102
newParent = newParent2;
102103
}
103104
}
104-
return value;
105+
return null;
105106
} else if (node instanceof ArrayNode) {
106107
ArrayNode arrayRoot = (ArrayNode) node;
107108
int position = getPosition(arrayRoot.height, key);
108109
Node child = arrayRoot.getChild(position);
109110
if (child==null) {
110111
// Found an empty slot in parent
111112
arrayRoot.addChild(position, new KeyValueNode<V>(arrayRoot, key, value));
112-
return value;
113+
return null;
113114
}
114115
return put(arrayRoot, child, (byte)(height+1), key, value);
115116
}
@@ -125,11 +126,10 @@ public V put(K key, V value) {
125126
V toReturn = null;
126127
if (root==null) {
127128
root = new KeyValueNode<V>(null, intKey, value);
128-
toReturn = value;
129129
} else {
130130
toReturn = put(null, root, (byte)0, intKey, value);
131131
}
132-
if (toReturn!=null) size++;
132+
if (toReturn==null) size++;
133133
return toReturn;
134134
}
135135

@@ -212,6 +212,15 @@ public V remove(K key) {
212212
return value;
213213
}
214214

215+
/**
216+
* {@inheritDoc}
217+
*/
218+
@Override
219+
public void clear() {
220+
root = null;
221+
size = 0;
222+
}
223+
215224
/**
216225
* {@inheritDoc}
217226
*/
@@ -314,7 +323,7 @@ private void unset(int position) {
314323
/**
315324
* Is the bit at position set (zero based)
316325
*
317-
* e.g. bitmap=01110 position=3 result=00110
326+
* e.g. bitmap=01110 position=3 result=true
318327
*/
319328
private boolean isSet(int position) {
320329
return ((bitmap &(1 << position)) >>> position)==1;
@@ -469,7 +478,7 @@ private static <K, V> String getString(Node parent, Node node, int height, Strin
469478
*/
470479
@Override
471480
public Map<K,V> toMap() {
472-
return (new JavaCompatibleHashMap<K,V>(this));
481+
return (new JavaCompatibleMap<K,V>(this));
473482
}
474483

475484
private static class JavaCompatibleIteratorWrapper<K,V> implements java.util.Iterator<java.util.Map.Entry<K, V>> {
@@ -524,11 +533,11 @@ public JavaCompatibleMapEntry(K key, V value) {
524533
}
525534
}
526535

527-
private static class JavaCompatibleHashMap<K, V> extends java.util.AbstractMap<K,V> {
536+
private static class JavaCompatibleMap<K, V> extends java.util.AbstractMap<K,V> {
528537

529538
private HashArrayMappedTrie<K,V> map = null;
530539

531-
protected JavaCompatibleHashMap(HashArrayMappedTrie<K,V> map) {
540+
protected JavaCompatibleMap(HashArrayMappedTrie<K,V> map) {
532541
this.map = map;
533542
}
534543

@@ -548,6 +557,14 @@ public V remove(Object key) {
548557
return map.remove((K)key);
549558
}
550559

560+
/**
561+
* {@inheritDoc}
562+
*/
563+
@Override
564+
public void clear() {
565+
map.clear();
566+
}
567+
551568
/**
552569
* {@inheritDoc}
553570
*/

0 commit comments

Comments
 (0)