Added utilities and a hashmap inverter.

This commit is contained in:
Harrison Deng 2020-04-19 18:17:17 -05:00
parent 08a23c1bf2
commit 23f761c36f
2 changed files with 80 additions and 0 deletions

View File

@ -0,0 +1,21 @@
package ca.recrown.islandsurvivalcraft;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
public class Utilities {
public static <K, V> HashMap<V, ArrayList<K>> invertHashMap(HashMap<K, V> hashMap) {
HashMap<V, ArrayList<K>> res = new HashMap<>();
for (Entry<K, V> entry : hashMap.entrySet()) {
if (!res.containsKey(entry.getValue())) {
ArrayList<K> l = new ArrayList<K>();
l.add(entry.getKey());
res.put(entry.getValue(), l);
} else {
res.get(entry.getValue()).add(entry.getKey());
}
}
return res;
}
}

View File

@ -0,0 +1,59 @@
package ca.recrown.islandsurvivalcraft;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class UtilitiesTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public UtilitiesTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( UtilitiesTest.class );
}
/**
* Basic hashmap inversion test.
*/
public void testInvertHashMap()
{
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("a", 1);
hashMap.put("b", 1);
hashMap.put("c", 2);
hashMap.put("d", 2);
HashMap<Integer, ArrayList<String>> res = Utilities.invertHashMap(hashMap);
ArrayList<String> first = res.get(1);
ArrayList<String> expectedFirst = new ArrayList<>();
expectedFirst.add("a");
expectedFirst.add("b");
ArrayList<String> second = res.get(2);
ArrayList<String> expectedSecond = new ArrayList<>();
expectedSecond.add("c");
expectedSecond.add("d");
assertEquals(first, expectedFirst);
assertEquals(second, expectedSecond);
}
}