Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • sarafa/p2
  • mertht/p2
  • cse332-19au/p2
  • sandchow/p2
  • hanzhang/p2
  • cse332-19sp/p2
  • cse332-20sp/p2
  • cse332-20su-tasks/p2
  • cse332-20su/p2
  • cse332-21su/p2
  • cse332-21wi/p2
  • cse332-21sp/p2
  • cse332-20au/p2
13 results
Show changes
Showing
with 1221 additions and 0 deletions
package tests.gitlab.ckpt1;
import cse332.interfaces.worklists.PriorityWorkList;
import datastructures.worklists.MinFourHeapComparable;
import org.junit.Before;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import static org.junit.Assert.*;
public class MinFourHeapComparableTests extends WorklistGradingTests {
private static Random RAND;
@Before
public void init() {
STUDENT_STR = new MinFourHeapComparable<>();
STUDENT_DOUBLE = new MinFourHeapComparable<>();
STUDENT_INT = new MinFourHeapComparable<>();
RAND = new Random(42);
}
@Test(timeout = 3000)
public void testHeapWith5Items() {
PriorityWorkList<String> heap = new MinFourHeapComparable<>();
String[] tests = { "a", "b", "c", "d", "e" };
for (int i = 0; i < 5; i++) {
String str = tests[i] + "a";
heap.add(str);
}
for (int i = 0; i < 5; i++) {
String str_heap = heap.next();
String str = (char) ('a' + i) + "a";
assertEquals(str, str_heap);
}
}
@Test(timeout = 3000)
public void testOrderingDoesNotMatter() {
PriorityWorkList<String> ordered = new MinFourHeapComparable<>();
PriorityWorkList<String> reversed = new MinFourHeapComparable<>();
PriorityWorkList<String> random = new MinFourHeapComparable<>();
addAll(ordered, new String[]{"a", "b", "c", "d", "e"});
addAll(reversed, new String[]{"e", "d", "c", "b", "a"});
addAll(random, new String[]{"d", "b", "c", "e", "a"});
assertTrue(isSame("a", ordered.peek(), reversed.peek(), random.peek()));
assertTrue(isSame("a", ordered.next(), reversed.next(), random.next()));
assertTrue(isSame("b", ordered.next(), reversed.next(), random.next()));
addAll(ordered, new String[] {"a", "a", "b", "c", "z"});
addAll(reversed, new String[] {"z", "c", "b", "a", "a"});
addAll(random, new String[] {"c", "z", "a", "b", "a"});
String[] expected = new String[] {"a", "a", "b", "c", "c", "d", "e", "z"};
for (String e : expected) {
assertTrue(isSame(e, ordered.peek(), reversed.peek(), random.peek()));
assertTrue(isSame(e, ordered.next(), reversed.next(), random.next()));
}
}
private boolean isSame(String... args) {
String first = args[0];
for (String arg : args) {
if (!first.equals(arg)) {
return false;
}
}
return true;
}
@Test(timeout = 3000)
public void testHugeHeap() {
PriorityWorkList<String> heap = new MinFourHeapComparable<>();
int n = 10000;
// Add them
for (int i = 0; i < n; i++) {
String str = String.format("%05d", i * 37 % n);
heap.add(str);
}
// Delete them all
for (int i = 0; i < n; i++) {
String s = heap.next();
assertEquals(i , Integer.parseInt(s));
}
}
@Test(timeout = 3000)
public void testWithCustomComparable() {
PriorityWorkList<Coordinate> student = new MinFourHeapComparable<>();
Queue<Coordinate> reference = new PriorityQueue<>();
for (int i = 0; i < 10000; i++) {
Coordinate coord = new Coordinate(RAND.nextInt(10000) - 5000, RAND.nextInt(10000) - 5000);
student.add(coord);
reference.add(coord);
}
assertEquals(reference.size(), student.size());
while (!reference.isEmpty()) {
assertEquals(reference.peek() , student.peek());
assertEquals(reference.remove() , student.next());
}
}
public static class Coordinate implements Comparable<Coordinate> {
private int x;
private int y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
// What exactly this comparable method is doing is somewhat arbitrary.
public int compareTo(Coordinate other) {
if (this.x != other.x) {
return this.x - other.x;
} else {
return this.y - other.y;
}
}
}
@Test(timeout = 3000)
public void checkStructure() {
PriorityWorkList<Integer> heap = new MinFourHeapComparable<>();
addAll(heap, new Integer[] {10, 10, 15, 1, 17, 16, 100, 101, 102, 103, 105, 106, 107, 108});
Object[] heapData = getField(heap, "data");
String heapStr = Arrays.toString(heapData);
String heapExp = "[1, 10, 15, 10, 17, 16, 100, 101, 102, 103, 105, 106, 107, 108";
heap.next();
heap.next();
heap.next();
Object[] heapData2 = getField(heap, "data");
String heapStr2 = Arrays.toString(heapData2);
String heapExp2 = "[15, 16, 103, 107, 17, 108, 100, 101, 102, 106, 105,";
assertTrue(heapStr.contains(heapExp));
assertTrue(heapStr2.contains(heapExp2));
}
protected <T> T getField(Object o, String fieldName) {
try {
Field field = o.getClass().getSuperclass().getDeclaredField(fieldName);
field.setAccessible(true);
Object f = field.get(o);
return (T) f;
} catch (Exception var6) {
try {
Field field = o.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Object f = field.get(o);
return (T) f;
} catch (Exception var5) {
return null;
}
}
}
}
package tests.gitlab.ckpt1;
import java.util.Arrays;
import cse332.datastructures.containers.Item;
import datastructures.dictionaries.MoveToFrontList;
import org.junit.Test;
import static org.junit.Assert.*;
public class MoveToFrontListTests {
@SuppressWarnings("unchecked")
@Test(timeout = 3000)
public void checkStructure() {
MoveToFrontList<Integer, Integer> list = new MoveToFrontList<Integer, Integer>();
int[] arr = {6, 5, 10, 14, 10, 31, 10, 13, 10, 10, 12, 10, 14, 10, 10, 11, 10, 14, 9, 8, 3, 2, 1, 0, 7, 4};
for(int i = 0; i < arr.length; i++) {
Integer oldValue = list.find(arr[i]);
if (oldValue == null) {
list.insert(arr[i], 1);
} else {
list.insert(arr[i], 1 + oldValue);
}
}
// Convert iterator to string
Item<Integer, Integer>[] dcs = (Item<Integer, Integer>[])new Item[list.size()];
int i = 0;
for (Item<Integer, Integer> item : list) {
dcs[i++] = item;
}
// Compare strings to make sure we get the right one
// Can use list.toString as well, but I'm not sure if students may modify that
String mtf_correct = "[4=1, 7=1, 0=1, 1=1, 2=1, 3=1, 8=1, 9=1, 14=3, 10=9, 11=1, 12=1, 13=1, 31=1, 5=1, 6=1]";
String mtf_test = Arrays.toString(dcs);
assertEquals(mtf_correct, mtf_test);
}
@Test(timeout = 3000)
public void testHugeMTFList() {
MoveToFrontList<String, Integer> list = new MoveToFrontList<>();
int n = 1000;
// Add them
for (int i = 0; i < 5 * n; i++) {
int k = (i % n) * 37 % n;
String str = String.format("%05d", k);
for (int j = 0; j < k + 1; j ++)
list.insert(str, list.find(str) == null ? 1 : list.find(str) + 1);
}
// Delete them all
int totalCount = 0;
for (Item<String, Integer> dc : list) {
assertEquals((Integer.parseInt(dc.key) + 1) * 5, dc.value.intValue());
totalCount += dc.value;
}
// Check sizes
assertEquals(totalCount, (n * (n + 1)) / 2 * 5);
assertEquals(list.size(), n);
assertNotNull(list.find("00851"));
assertEquals(list.find("00851").intValue(), 4260);
}
}
package tests.gitlab.ckpt1;
import cse332.interfaces.worklists.WorkList;
import org.junit.Test;
import java.util.NoSuchElementException;
import static org.junit.Assert.*;
public abstract class WorklistGradingTests {
protected static WorkList<String> STUDENT_STR;
protected static WorkList<Double> STUDENT_DOUBLE;
protected static WorkList<Integer> STUDENT_INT;
@Test(timeout = 3000)
public void testHasWork() {
assertFalse(STUDENT_INT.hasWork());
}
@Test(timeout = 3000)
public void testHasWorkAfterAdd() {
STUDENT_INT.add(1);
assertTrue(STUDENT_INT.hasWork());
}
@Test(timeout = 3000)
public void testHasWorkAfterAddRemove() {
for (int i = 0; i < 1000; i++) {
STUDENT_DOUBLE.add(Math.random());
}
for (int i = 0; i < 1000; i++) {
STUDENT_DOUBLE.next();
}
assertFalse(STUDENT_DOUBLE.hasWork());
}
@Test(timeout = 3000)
public void testPeekHasException() {
assertTrue(doesPeekThrowException(STUDENT_INT));
addAndRemove(STUDENT_INT, 42, 10);
assertTrue(doesPeekThrowException(STUDENT_INT));
}
@Test(timeout = 3000)
public void testNextHasException() {
assertTrue(doesNextThrowException(STUDENT_INT));
addAndRemove(STUDENT_INT, 42, 10);
assertTrue(doesNextThrowException(STUDENT_INT));
}
@Test(timeout = 3000)
public void testClear() {
addAll(STUDENT_STR, new String[]{"Beware", "the", "Jabberwock", "my", "son!"});
assertTrue(STUDENT_STR.hasWork());
assertEquals(5, STUDENT_STR.size());
STUDENT_STR.clear();
assertFalse(STUDENT_STR.hasWork());
assertEquals(0, STUDENT_STR.size());
assertTrue(doesPeekThrowException(STUDENT_STR));
assertTrue(doesNextThrowException(STUDENT_STR));
}
// UTILITY METHODS
protected static <E> void addAll(WorkList<E> worklist, E[] values) {
for (E value : values) {
worklist.add(value);
}
}
protected static <E> void addAndRemove(WorkList<E> worklist, E value, int amount) {
for (int i = 0; i < amount; i++) {
worklist.add(value);
}
for (int i = 0; i < amount; i++) {
worklist.next();
}
}
protected static <E> boolean doesPeekThrowException(WorkList<E> worklist) {
try {
worklist.peek();
} catch (NoSuchElementException e) {
return true;
}
return false;
}
protected static <E> boolean doesNextThrowException(WorkList<E> worklist) {
try {
worklist.next();
} catch (NoSuchElementException e) {
return true;
}
return false;
}
}
package tests.gitlab.ckpt2;
import cse332.datastructures.containers.Item;
import cse332.datastructures.trees.BinarySearchTree.BSTNode;
import cse332.interfaces.misc.Dictionary;
import datastructures.dictionaries.AVLTree;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import org.junit.Test;
import static org.junit.Assert.*;
public class AVLTreeTests {
private AVLTree<String, Integer> init() {
return new AVLTree<>();
}
private <E extends Comparable<E>> void incCount(Dictionary<E, Integer> tree, E key) {
Integer value = tree.find(key);
if (value == null) {
tree.insert(key, 1);
} else {
tree.insert(key, value + 1);
}
}
@SuppressWarnings("rawtypes")
@Test(timeout = 3000)
public void checkStructure() {
AVLTree<Integer, Integer> tree = new AVLTree<>();
incCount(tree, 10);
incCount(tree, 14);
incCount(tree, 10);
incCount(tree, 31);
incCount(tree, 10);
incCount(tree, 13);
incCount(tree, 10);
incCount(tree, 10);
incCount(tree, 12);
incCount(tree, 10);
incCount(tree, 13);
incCount(tree, 10);
incCount(tree, 10);
incCount(tree, 11);
incCount(tree, 10);
incCount(tree, 14);
incCount(tree, 9);
incCount(tree, 8);
incCount(tree, 7);
incCount(tree, 6);
incCount(tree, 5);
incCount(tree, 4);
incCount(tree, 3);
incCount(tree, 2);
incCount(tree, 1);
incCount(tree, 0);
// {10, 14, 10, 31, 10, 13, 10, 10, 12, 10, 13, 10, 10, 11, 10, 14, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}
// {10, 14, 31, 13, 12, 11, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}
BSTNode root = (BSTNode) getField(tree, "root");
String trueData = " [8 [4 [2 [1 [0..].] [3..]] [6 [5..] [7..]]] [12 [10 [9..] [11..]] [14 [13..] [31..]]]]";
String trueCounts = " [1 [1 [1 [1 [1..].] [1..]] [1 [1..] [1..]]] [1 [9 [1..] [1..]] [2 [2..] [1..]]]]";
// String trueData = " [10 [6 [2 [1 [0..].] [4 [3..] [5..]]] [8 [7..] [9..]]] [13 [12 [11..].] [14. [31..]]]]";
// String trueCounts = " [9 [1 [1 [1 [1..].] [1 [1..] [1..]]] [1 [1..] [1..]]] [2 [1 [1..].] [2. [1..]]]]";
// System.err.println(nestd(root));
// System.err.println(trueData);
assertEquals(trueData, nestd(root));
assertEquals(trueCounts, nestc(root));
}
@SuppressWarnings("rawtypes")
public String nestd(BSTNode root) {
if(root == null)
return ".";
return " [" + root.key + nestd(root.children[0]) + nestd(root.children[1]) + "]";
}
@SuppressWarnings("rawtypes")
public String nestc(BSTNode root) {
if(root == null)
return ".";
return " [" + root.value + nestc(root.children[0]) + nestc(root.children[1]) + "]";
}
@Test(timeout = 3000)
public void testTreeWith5Items() {
AVLTree<String, Integer> tree = init();
String[] tests_struct = { "a", "b", "c", "d", "e" };
String[] tests = { "b", "d", "e", "c", "a" };
for (int i = 0; i < 5; i++) {
String str = tests[i] + "a";
incCount(tree, str);
}
int i = 0;
for (Item<String, Integer> item : tree) {
String str_heap = item.key;
String str = tests_struct[i] + "a";
assertEquals(str, str_heap);
i++;
}
}
@Test(timeout = 3000)
public void testHugeTree() {
AVLTree<String, Integer> tree = init();
int n = 1000;
// Add them
for (int i = 0; i < 5 * n; i++) {
int k = (i % n) * 37 % n;
String str = String.format("%05d", k);
for (int j = 0; j < k + 1; j ++)
incCount(tree, str);
}
// Calculate count of all values in tree
int totalCount = 0;
for (Item<String, Integer> dc : tree) {
assertEquals((Integer.parseInt(dc.key) + 1) * 5, dc.value.intValue());
totalCount += dc.value;
}
// Check for accuracy
assertEquals((n * (n + 1)) / 2 * 5, totalCount);
assertEquals(n, tree.size());
assertNotNull(tree.find("00851"));
assertEquals(4260, (int) tree.find("00851"));
}
/**
* Get a field from an object
* @param o Object you want to get the field from
* @param fieldName Name of the field
* @return
*/
@SuppressWarnings("unchecked")
private <T> T getField(Object o, String fieldName) {
try {
Field field = o.getClass().getSuperclass().getDeclaredField(fieldName);
field.setAccessible(true);
Object f = field.get(o);
return (T) f;
} catch (Exception e) {
try {
Field field = o.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Object f = field.get(o);
return (T) f;
} catch (Exception e2) {
return null;
}
}
}
}
package tests.gitlab.ckpt2;
import datastructures.worklists.CircularArrayFIFOQueue;
import org.junit.Test;
import static org.junit.Assert.*;
public class CircularArrayHashCodeTests {
private CircularArrayFIFOQueue<String> init() {
return new CircularArrayFIFOQueue<String>(10);
}
@Test(timeout = 3000)
public void equality() {
CircularArrayFIFOQueue<String> l1 = init();
CircularArrayFIFOQueue<String> l2 = init();
for (int i = 0; i < 3; i++) {
l1.add("a");
l2.add("a");
}
assertEquals(l1.hashCode(), l2.hashCode());
}
@Test(timeout = 3000)
public void ineq1() {
CircularArrayFIFOQueue<String> l1 = init();
CircularArrayFIFOQueue<String> l2 = init();
l1.add("a");
l1.add("a");
l1.add("b");
l2.add("a");
l2.add("a");
l2.add("a");
assertNotEquals(l1.hashCode(), l2.hashCode());
}
@Test(timeout = 3000)
public void ineq2() {
CircularArrayFIFOQueue<String> l1 = init();
CircularArrayFIFOQueue<String> l2 = init();
l1.add("a");
l1.add("a");
l1.add("a");
l1.add("a");
l2.add("a");
l2.add("a");
l2.add("a");
assertNotEquals(l1.hashCode() , l2.hashCode());
}
@Test(timeout = 3000)
public void ineq3() {
CircularArrayFIFOQueue<String> l1 = init();
CircularArrayFIFOQueue<String> l2 = init();
l1.add("a");
l1.add("b");
l1.add("c");
l2.add("c");
l2.add("b");
l2.add("a");
assertNotEquals(l1.hashCode() , l2.hashCode());
}
@Test(timeout = 3000)
public void equality_consistent_with_hashcode() {
CircularArrayFIFOQueue<String> l1 = init();
CircularArrayFIFOQueue<String> l2 = init();
l1.add("a");
l1.add("b");
l2.add("a");
l2.add("b");
assertEquals(l1 , l2);
assertEquals(l1.hashCode() , l2.hashCode());
}
}
package tests.gitlab.ckpt2;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
AVLTreeTests.class,
HashTableTests.class,
CircularArrayHashCodeTests.class,
QuickSortTests.class,
TopKSortTests.class,
HeapSortTests.class,
HashTrieMapTests.class,
MinFourHeapTests.class
})
public class Ckpt2Tests {
}
package tests.gitlab.ckpt2;
import cse332.datastructures.containers.Item;
import cse332.interfaces.misc.Dictionary;
import datastructures.dictionaries.ChainingHashTable;
import datastructures.dictionaries.MoveToFrontList;
import org.junit.Test;
import static org.junit.Assert.*;
public class HashTableTests {
private void incCount(Dictionary<String, Integer> list, String key) {
Integer find = list.find(key);
if (find == null)
list.insert(key, 1);
else
list.insert(key, 1 + find);
}
@Test(timeout = 3000)
public void testHugeHashTable() {
ChainingHashTable<String, Integer> list = new ChainingHashTable<>(MoveToFrontList::new);
int n = 1000;
// Add them
for (int i = 0; i < 5 * n; i++) {
int k = (i % n) * 37 % n;
String str = String.format("%05d", k);
for (int j = 0; j < k + 1; j ++)
incCount(list, str);
}
// Delete them all
int totalCount = 0;
for (Item<String, Integer> dc : list) {
assertEquals((Integer.parseInt(dc.key) + 1) * 5, (int) dc.value);
totalCount += dc.value;
}
assertEquals(totalCount, (n * (n + 1)) / 2 * 5);
assertEquals(list.size(), n);
assertNotNull(list.find("00851"));
assertEquals(4260, (int) list.find("00851"));
}
}
package tests.gitlab.ckpt2;
import cse332.types.AlphabeticString;
import datastructures.dictionaries.HashTrieMap;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class HashTrieMapTests {
protected static HashTrieMap<Character, AlphabeticString, String> STUDENT;
@Before
public void init() {
STUDENT = new HashTrieMap<>(AlphabeticString.class);
}
/**
* Tests if insert, find, and findPrefix work in general.
*/
@Test(timeout = 3000)
public void testBasic() {
String[] words = {"dog", "doggy", "doge", "dragon", "cat", "draggin"};
String[] invalid = {"d", "cataract", "", "do"};
addAll(STUDENT, words);
assertTrue(containsAllPaths(STUDENT, words));
assertTrue(doesNotContainAll(STUDENT, invalid));
}
/**
* Test findPrefix more rigorously.
*/
@Test(timeout = 3000)
public void testFindPrefixes() {
String[] words = {"dog", "doggy", "doge", "dragon", "cat", "draggin"};
addAll(STUDENT, words);
assertTrue(containsAllPrefixes(STUDENT, "d", "", "do"));
assertTrue(doesNotContainAllPrefixes(STUDENT, "batarang", "dogee", "dragging"));
}
/**
* Tests that trying to find a non-existent entity does the correct thing
*/
@Test(timeout = 3000)
public void testFindNonexistentDoesNotCrash() {
addAll(STUDENT, "foo", "bar", "baz");
assertNull(STUDENT.find(a("orangutan")));
assertNull(STUDENT.find(a("z")));
assertNull(STUDENT.find(a("ba")));
assertNull(STUDENT.find(a("bazz")));
assertFalse(STUDENT.findPrefix(a("boor")));
assertFalse(STUDENT.findPrefix(a("z")) );
}
@Test(timeout = 3000, expected = IllegalArgumentException.class)
public void testFindingNullKeyCausesError() {
STUDENT.find(null);
}
@Test(timeout = 3000, expected = IllegalArgumentException.class)
public void testFindingNullPrefixCausesError() {
STUDENT.findPrefix(null);
}
/**
* Tests that inserts correctly wipe out old values.
*/
@Test(timeout = 3000)
public void testInsertReplacesOldValue() {
AlphabeticString key = a("myKey");
assertNull(STUDENT.insert(key, "foo"));
assertEquals("foo", STUDENT.insert(key, "bar"));
assertEquals("bar", STUDENT.insert(key, "baz"));
}
@Test(timeout = 3000, expected = IllegalArgumentException.class)
public void testInsertingNullKeyCausesError() {
STUDENT.insert(null, "foo");
}
@Test(timeout = 3000, expected = IllegalArgumentException.class)
public void testInsertingNullValueCausesError() {
STUDENT.insert(a("foo"), null);
}
@Test(timeout = 3000, expected=UnsupportedOperationException.class)
public void testDeletingCausesError() {
STUDENT.insert(a("foo"), "doo");
STUDENT.delete(a("foo"));
}
@Test(timeout = 3000, expected=UnsupportedOperationException.class)
public void testClearCausesError() {
STUDENT.insert(a("foo"), "doo");
STUDENT.clear();
}
@Test(timeout = 3000)
public void checkUnderlyingStructure() {
STUDENT.insert(a(""), "A");
STUDENT.insert(a("foo"), "B");
STUDENT.insert(a("fez"), "C");
STUDENT.insert(a("fezzy"), "D");
STUDENT.insert(a("jazz"), "E");
STUDENT.insert(a("jazzy"), "F");
MockNode fullExpected = node("A")
.branch('f', node()
.branch('o', node()
.branch('o', node("B")))
.branch('e', node()
.branch('z', node("C")
.branch('z', node()
.branch('y', node("D"))))))
.branch('j', node()
.branch('a', node()
.branch('z', node()
.branch('z', node("E")
.branch('y', node("F"))))));
assertTrue(equals(fullExpected, getField(STUDENT, "root")));
}
protected static boolean equals(MockNode expected, HashTrieMap<Character, AlphabeticString, String>.HashTrieNode student) {
if (expected == null && student == null) {
return true;
} else if (expected == null || student == null) {
// If only one of the two is null
return false;
} else if (expected.value != null && !expected.value.equals(student.value)) {
// If values don't match
return false;
} else if (expected.value == null && student.value != null) {
// If only one of the values are null
return false;
} else if (expected.pointers.size() != student.pointers.size()) {
// If number of pointers is not the same
return false;
} else {
return true;
}
}
protected static MockNode node() {
return new MockNode();
}
protected static MockNode node(String value) {
return new MockNode(value);
}
protected static class MockNode {
public Map<Character, MockNode> pointers;
public String value;
public MockNode() {
this(null);
}
public MockNode(String value) {
this.pointers = new HashMap<>();
this.value = value;
}
public MockNode branch(char c, MockNode child) {
this.pointers.put(c, child);
return this;
}
}
@Test(timeout = 3000)
public void stressTest() {
// Should contain 30 characters
char[] symbols = "abcdefghijklmnopqrstuvwxyz!@#$".toCharArray();
long i = 0;
for (char a : symbols) {
for (char b : symbols) {
for (char c : symbols) {
for (char d : symbols) {
Character[] word = new Character[]{a, b, c, d};
STUDENT.insert(new AlphabeticString(word), "" + i);
i += 1;
}
}
}
}
for (char a : symbols) {
for (char b : symbols) {
assertTrue(STUDENT.findPrefix(new AlphabeticString(new Character[]{a, b})));
}
}
i = 0;
for (char a : symbols) {
for (char b : symbols) {
for (char c : symbols) {
for (char d : symbols) {
Character[] word = new Character[]{a, b, c, d};
assertEquals("" + i, STUDENT.find(new AlphabeticString(word)));
i += 1;
}
}
}
}
}
/**
* Converts a String into an AlphabeticString
*/
private static AlphabeticString a(String s) {
return new AlphabeticString(s);
}
/**
* Checks if the trie contains the word and the expected value, and that all prefixes of
* the word exist in the trie.
*/
private static boolean containsPath(HashTrieMap<Character, AlphabeticString, String> trie, String word, String expectedValue) {
AlphabeticString key = a(word);
boolean valueCorrect = expectedValue.equals(trie.find(key));
boolean fullWordIsPrefix = trie.findPrefix(key);
boolean invalidWordDoesNotExist = trie.find(a(word + "$")) == null;
if (!valueCorrect || !fullWordIsPrefix || !invalidWordDoesNotExist) {
return false;
}
return allPrefixesExist(trie, word);
}
/**
* Checks if the trie contains the word, and that all prefixes of the word exist in the trie.
*
* Assumes that the expected value is word.toUpperCase().
*/
private static boolean containsPath(HashTrieMap<Character, AlphabeticString, String> trie, String word) {
return containsPath(trie, word, word.toUpperCase());
}
/**
* Returns true if all prefixes of a word exist in the trie.
*
* That is, if we do `trie.insert(new AlphabeticString("dog"), "some-value")`, this method
* would check to see if "dog", "do", "d", and "" are all prefixes of the trie.
*/
private static boolean allPrefixesExist(HashTrieMap<Character, AlphabeticString, String> trie, String word) {
String accum = "";
for (char c : word.toCharArray()) {
accum += c;
if (!trie.findPrefix(a(accum))) {
return false;
}
}
return true;
}
private static boolean containsAllPaths(HashTrieMap<Character, AlphabeticString, String> trie, String... words) {
for (String word : words) {
if (!containsPath(trie, word)) {
return false;
}
}
return true;
}
private static boolean doesNotContainAll(HashTrieMap<Character, AlphabeticString, String> trie, String... words) {
for (String word : words) {
if (trie.find(a(word)) != null) {
return false;
}
}
return true;
}
private static boolean containsAllPrefixes(HashTrieMap<Character, AlphabeticString, String> trie, String... words) {
for (String word : words) {
if (!trie.findPrefix(a(word))) {
return false;
}
}
return true;
}
private static boolean doesNotContainAllPrefixes(HashTrieMap<Character, AlphabeticString, String> trie, String... words) {
for (String word : words) {
if (trie.findPrefix(a(word))) {
return false;
}
}
return true;
}
private static void addAll(HashTrieMap<Character, AlphabeticString, String> trie, String... words) {
for (String word : words) {
trie.insert(a(word), word.toUpperCase());
}
}
protected <T> T getField(Object o, String fieldName) {
try {
Field field = o.getClass().getSuperclass().getDeclaredField(fieldName);
field.setAccessible(true);
Object f = field.get(o);
return (T) f;
} catch (Exception var6) {
try {
Field field = o.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Object f = field.get(o);
return (T) f;
} catch (Exception var5) {
return null;
}
}
}
}
package tests.gitlab.ckpt2;
import p2.sorts.HeapSort;
import org.junit.Test;
import java.util.Comparator;
import static org.junit.Assert.*;
public class HeapSortTests {
@Test(timeout = 3000)
public void integer_sorted() {
Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer[] arr_sorted = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
HeapSort.sort(arr, Integer::compareTo);
for(int i = 0; i < arr.length; i++) {
assertEquals(arr[i], arr_sorted[i]);
}
}
@Test(timeout = 3000)
public void integer_random() {
Integer[] arr = {3, 1, 4, 5, 9, 2, 6, 7, 8};
Integer[] arr_sorted = {1, 2, 3, 4, 5, 6, 7, 8, 9};
HeapSort.sort(arr, Integer::compareTo);
for(int i = 0; i < arr.length; i++) {
assertEquals(arr[i], arr_sorted[i]);
}
}
}
package tests.gitlab.ckpt2;
import cse332.interfaces.worklists.PriorityWorkList;
import datastructures.worklists.MinFourHeap;
import org.junit.Before;
import org.junit.Test;
import tests.gitlab.ckpt1.WorklistGradingTests;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import static org.junit.Assert.*;
public class MinFourHeapTests extends WorklistGradingTests {
private static Random RAND;
@Before
public void init() {
STUDENT_STR = new MinFourHeap<>(String::compareTo);
STUDENT_DOUBLE = new MinFourHeap<>(Double::compareTo);
STUDENT_INT = new MinFourHeap<>(Integer::compareTo);
RAND = new Random(42);
}
@Test(timeout = 3000)
public void testHeapWith5Items() {
PriorityWorkList<String> heap = new MinFourHeap<>(String::compareTo);
String[] tests = { "a", "b", "c", "d", "e" };
for (int i = 0; i < 5; i++) {
String str = tests[i] + "a";
heap.add(str);
}
for (int i = 0; i < 5; i++) {
String str_heap = heap.next();
String str = (char) ('a' + i) + "a";
assertEquals(str, str_heap);
}
}
@Test(timeout = 3000)
public void testOrderingDoesNotMatter() {
PriorityWorkList<String> ordered = new MinFourHeap<>(String::compareTo);
PriorityWorkList<String> reversed = new MinFourHeap<>(String::compareTo);
PriorityWorkList<String> random = new MinFourHeap<>(String::compareTo);
addAll(ordered, new String[]{"a", "b", "c", "d", "e"});
addAll(reversed, new String[]{"e", "d", "c", "b", "a"});
addAll(random, new String[]{"d", "b", "c", "e", "a"});
assertTrue(isSame("a", ordered.peek(), reversed.peek(), random.peek()));
assertTrue(isSame("a", ordered.next(), reversed.next(), random.next()));
assertTrue(isSame("b", ordered.next(), reversed.next(), random.next()));
addAll(ordered, new String[] {"a", "a", "b", "c", "z"});
addAll(reversed, new String[] {"z", "c", "b", "a", "a"});
addAll(random, new String[] {"c", "z", "a", "b", "a"});
String[] expected = new String[] {"a", "a", "b", "c", "c", "d", "e", "z"};
for (String e : expected) {
assertTrue(isSame(e, ordered.peek(), reversed.peek(), random.peek()));
assertTrue(isSame(e, ordered.next(), reversed.next(), random.next()));
}
}
private boolean isSame(String... args) {
String first = args[0];
for (String arg : args) {
if (!first.equals(arg)) {
return false;
}
}
return true;
}
@Test(timeout = 3000)
public void testHugeHeap() {
PriorityWorkList<String> heap = new MinFourHeap<>(String::compareTo);
int n = 10000;
// Add them
for (int i = 0; i < n; i++) {
String str = String.format("%05d", i * 37 % n);
heap.add(str);
}
// Delete them all
for (int i = 0; i < n; i++) {
String s = heap.next();
assertEquals(i , Integer.parseInt(s));
}
}
@Test(timeout = 3000)
public void testWithCustomComparable() {
PriorityWorkList<Coordinate> student = new MinFourHeap<>(Coordinate::compareTo);
Queue<Coordinate> reference = new PriorityQueue<>();
for (int i = 0; i < 10000; i++) {
Coordinate coord = new Coordinate(RAND.nextInt(10000) - 5000, RAND.nextInt(10000) - 5000);
student.add(coord);
reference.add(coord);
}
assertEquals(reference.size(), student.size());
while (!reference.isEmpty()) {
assertEquals(reference.peek() , student.peek());
assertEquals(reference.remove() , student.next());
}
}
public static class Coordinate implements Comparable<Coordinate> {
private int x;
private int y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
// What exactly this comparable method is doing is somewhat arbitrary.
public int compareTo(Coordinate other) {
if (this.x != other.x) {
return this.x - other.x;
} else {
return this.y - other.y;
}
}
}
@Test(timeout = 3000)
public void checkStructure() {
PriorityWorkList<Integer> heap = new MinFourHeap<>(Integer::compareTo);
addAll(heap, new Integer[] {10, 10, 15, 1, 17, 16, 100, 101, 102, 103, 105, 106, 107, 108});
Object[] heapData = getField(heap, "data");
String heapStr = Arrays.toString(heapData);
String heapExp = "[1, 10, 15, 10, 17, 16, 100, 101, 102, 103, 105, 106, 107, 108";
heap.next();
heap.next();
heap.next();
Object[] heapData2 = getField(heap, "data");
String heapStr2 = Arrays.toString(heapData2);
String heapExp2 = "[15, 16, 103, 107, 17, 108, 100, 101, 102, 106, 105,";
assertTrue(heapStr.contains(heapExp));
assertTrue(heapStr2.contains(heapExp2));
}
protected <T> T getField(Object o, String fieldName) {
try {
Field field = o.getClass().getSuperclass().getDeclaredField(fieldName);
field.setAccessible(true);
Object f = field.get(o);
return (T) f;
} catch (Exception var6) {
try {
Field field = o.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Object f = field.get(o);
return (T) f;
} catch (Exception var5) {
return null;
}
}
}
}
package tests.gitlab.ckpt2;
import java.util.Comparator;
import p2.sorts.QuickSort;
import org.junit.Test;
import static org.junit.Assert.*;
public class QuickSortTests {
@Test(timeout = 3000)
public void integer_sorted() {
Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer[] arr_sorted = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
QuickSort.sort(arr, Integer::compareTo);
for(int i = 0; i < arr.length; i++) {
assertEquals(arr[i], arr_sorted[i]);
}
}
@Test(timeout = 3000)
public void integer_random() {
Integer[] arr = {3, 1, 4, 5, 9, 2, 6, 7, 8};
Integer[] arr_sorted = {1, 2, 3, 4, 5, 6, 7, 8, 9};
QuickSort.sort(arr, Integer::compareTo);
for(int i = 0; i < arr.length; i++) {
assertEquals(arr[i], arr_sorted[i]);
}
}
}
\ No newline at end of file
package tests.gitlab.ckpt2;
import java.util.Comparator;
import p2.sorts.TopKSort;
import org.junit.Test;
import static org.junit.Assert.*;
public class TopKSortTests {
@Test(timeout = 3000)
public void integer_sorted() {
int K = 4;
Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer[] arr_sorted = {7, 8, 9, 10};
TopKSort.sort(arr, K, Integer::compareTo);
for(int i = 0; i < K; i++) {
assertEquals(arr[i], arr_sorted[i]);
}
}
@Test(timeout = 3000)
public void integer_random() {
int K = 4;
Integer[] arr = {3, 1, 4, 5, 9, 2, 6, 7, 8};
Integer[] arr_sorted = {6, 7, 8, 9};
TopKSort.sort(arr, K, Integer::compareTo);
for(int i = 0; i < K; i++) {
assertEquals(arr[i], arr_sorted[i]);
}
}
}
\ No newline at end of file
No preview for this file type