ICS23q2fal11

Embed Size (px)

Citation preview

  • 8/3/2019 ICS23q2fal11

    1/2

  • 8/3/2019 ICS23q2fal11

    2/2

    4. (7 pts) AMapis an injection between keys and values when every value has exactly one key that maps

    to it. Or stated another way, a map is not aninjection if it has two keys that map to the same value.

    Complete the public static generic booleanmethod isInjection, which takes a Mapand determines

    whether or not it is an injection, according to either of the criteria stated above.

    Hint: Code this method by using a local variable that is Set(using theArraySetimplementation) and looking

    at every key and determining if its associated value has already been seen as an association from a previously

    examined key. An elegant (short/efficient) solution will get the most credit.

    public static boolean isInjection (Map m) {

    5. (3 pts) Complete the public static generic method nthGet, which takes a Mapmthat is a permutation

    (every key in it maps to a value that is also a key in the Map), a starting key k in the map, and a non-

    negative integer nand returns the nthkey gotten from the map starting with key k: ifnis 0return k; ifnis

    1return m.get(k); ifnis 2return m.get(m.get(k)); ifnis 3return m.get(m.get(m.get(k))); etc.: it

    does ncalls to get. Assume (do NOT check) that mis a permutation; but, throw an appropriate exception

    ifkis not a key in m, or ifn< 0(which includes ks and ns their actual values).

    public static K nthGet (Map m, K k, int n) {