2 DArrays and Maps Samples
2 DArrays and Maps Samples
This code constructs an array containing multiplication table for the given starting and ending integers.
The function returns the distance between the of the pair in the map of positions. The distance is the Manhattan
distance (i.e. the distance in terms of number of steps directly north, south, east, or west). So for example, given
the array:
aa.b
....
..b.
This function constructs a map associating a number with it's largest divisor. So for example,
numberToLargestDivisior(10) yields {2=1, 3=1, 4=2, 5=1, 6=3, 7=1, 8=4, 9=3, 10=5}
This function takes a map and returns a new map of where both the keys and values are double. So far
example,
{A=a, BB=bb} yields {AA=aa, BBBB=bbbb}
//hint – you might want to tear this page off so that you can refer to it
// if you want to get the dimensions, the usual length will give you the first
// dimension
System.out.println(myIntArray.length); //prints 50
//to get the second dimension, do it like this
System.out.println(myIntArray[0].length); //prints 7
// actually you could use any valid index instead of 0, but they'll
// all give you the same length
Map Intro
//hint – you might want to tear this page off so that you can refer to it
// A map is like a dictionary in Python
// It associates a key with a particular value - but because this is
// java they have to be typed
//
// Format: HashMap<KeyType,ValueType> foo = new HashMap<KeyType,ValueType>();
// e.g.
HashMap<String,Integer> namesToWeight = new HashMap<String,Integer>();
//note that putting twice with the same key overwrites the value
namesToWeight.put("Buffalo", 165);
//if you need to check if a particular key is in the map, use containsKey
if(namesToWeight.containsKey("Steve")) {
System.out.println("Steve is in the map!");
}
//if you need iterate over all the keys in the map, use the keyset
Set<String> keys = namesToWeight.keySet();
//it's annoying to iterate over a set. Use the enhanced for loop:
for(String key : keys) {
int value = namesToWeight.get(key);
//do something for every key and value
}