Week 8(Maps)

  1. Read http://java.sun.com/j2se/1.4.2/docs/api/java/util/AbstractMap.html.

  2. Try week5/WordSort.java on the file week5/rrr.

  3. Replace the TreeMap with HashMap in week5/WordSort.java and see the difference.

  4. A Map <String,Integer> can be thought of as a function which maps Strings to Integers.

    For example, if we run WordSort on rrr we get:

    ape : 3
    cat : 1
    dog : 1
    paper : 2
    rabbit : 3
    schlongle : 1
    

    This function can be inverted to a function which maps Integers to Sets of Strings as follows:

    1 : [cat, schlongle, dog]
    2 : [paper]
    3 : [rabbit, ape]
    

    Write a method whose heading is:

    public static TreeMap <Integer,HashSet <String>> invert (TreeMap<String,Integer> t)
    
    which produces a TreeMap which inverts the TreeMap in the way described. week5/WordSort1.java

  5. Write a generic class which generalises the notion of inverting a function. Solution

  6. Rewrite week5/WordSort1.java to use this generic invert. Solution

  7. (Easy Assignment) Rewrite Solution so we map each word to its first Character. i.e We now have

    TreeMap <String,Character> map = new TreeMap <String,Character>(  );
    
    Watch video about easy assignment for week 5

    Solution

  8. (Hard Assignment) Given the generic class
    
    
    public class pair <I,S> {
     
    I i;
    S s;  
     
    	public pair (I i1, S s1)
    	{
    		i=i1; s=s1;
    	
    	}
    
    	public String toString()
    	{
    		return "("+i+","+s+")";
    	}
    }
    
    Complete the following generic class:

    public class mapToSetPair <A,B> {
       public HashSet <pair<A,B>> make (TreeMap <A,HashSet <B>> t)
      {
      	 	
      }
     
     
    }
    
    Which from a function from A to Set(B) produces a HashSet of pairs in A X B. e.g. applied to rrr gives the set of pairs:
    (a,apple)
    (r,rock)
    (c,cat)
    (r,rabbit)
    (a,ape)
    (s,schlongle)
    (d,dog)
    (p,paper)
    

    Solution

    Adapt WordSort4.java to use it. Solution

    Week 8 Resources

s.danicic@gold.ac.uk
Sebastian Danicic BSc MSc PhD (Reader in Computer Science)
Dept of Computing, Goldsmiths, University of London, London SE14 6NW
Last updated 2015-09-04