2.20 More on Mutation with Structures
While I array all day
Array array array array array array array...
At the end: I’m done!
2.20.1 Objectives
what an array is
2.20.2 Exercises (due 2011/12/05 08:45:00)
1. Write a function called translateAll that takes an array of Posns, a dx, and a dy, and modifies the array such that it contains new Posns that have been translated.
2. Write a function called translateAllNoNew that takes an array of Posns, a dx, and a dy, and modifies the Posns such that they are all translated.
3. Recall binary search trees. Write a function call update which takes a BST, a key, and a string and returns a BST where the key’s value has been updated. Do not use mutation. You must make use of the BST property.
12 |
/ \ |
8 23 |
/\ / \ |
1 9 15 29 |
What is the fewest number of new nodes that must be created to update the tree so that 15 is mapped to "Fifteen" rather than "十五"?
4. Modify update to use mutation so that the node’s value is modified in place. Re-answer the side question about the example tree.
5. Write a function called ThreeDayMovingAverage that takes a list of prices, where each represents a day, and returns a list of 3 day price averages. For example, 1:2:3:4:! would return ((1+2+3)/3) : ((2+3+4)/3) : !
6. Modify ThreeDayMovingAverage so that it takes an array of prices and replaces the values with their moving averages. If there is not enough data for a three day average for the day, replace it with NaN. (Remember that NAN is a great way to get NaN.)
2.20.3 Optional Exercises (due 2011/12/12 08:45:00)
7. Write a function called anyTrue that takes an array of booleans and returns true if any is true. You must only use function calls: no while or for.
8. Write anyTrue using while or for
9. Write the function distances that takes an array of numbers and modifies the array such that each number is replaced with the difference between it and the previous number. For the first number, assume the previous number was 42.
2.20.4 Notes
These notes are primarily for my sake, but I don’t see any reason to hide them from you.
|
Write sums |
-- Replaces each element with itself added to all subsequent elements |
-- Write in accumulator style with a helper |
-- Translate to a for form |
-- Why: We can count down, we can develop with accumulator style and translate, even though there is other mutation going on |
|
Write andArray (boolean[]) |
-- We can have arrays of everything |
|
Write inPlaceSort (int[]) |
-- Refer to http://www.htdp.org/2003-09-26/Book/curriculum-Z-H-53.html (figures 126 and 127, for a refresher) |
|
== Congrats == |
|
You are a programmer! Go forth and conquer. |
|
Everything else is just learning the domains of existing libraries people have put together. |