CMU 15-112 Fall 2016: Fundamentals of Programming and Computer Science
Lab 1 (Due Saturday 3-Sep, at 6pm)




  1. nearestOdd(n)
    Write the function nearestOdd(n) that takes an int or float n, and returns as an int value the nearest odd number to n. In the case of a tie, return the smaller odd value.

  2. rectanglesOverlap(x1, y1, w1, h1, x2, y2, w2, h2)
    A rectangle can be described by its left, top, width, and height. This function takes two rectangles described this way, and returns True if the rectangles overlap at all (even if just at a point), and False otherwise. Note: here we will represent coordinates the way they are usually represented in computer graphics, where (0,0) is at the left-top corner of the screen, and while the x-coordinate goes up while you head right, the y-coordinate goes up while you head down. Yes, up is down! This is quite common in computer graphics, and is how Tkinter and Brython in particular both work. Check out the examples in the test code we provided to see this in action. Up is down. Weird, but true.

  3. isPerfectSquare(n)
    Write the function isPerfectSquare(n) that takes a possibly-non-int value, and returns True if it is an int that is a perfect square (that is, if there exists an integer m such that m**2 == n), and False otherwise. Do not crash on non-ints nor on negative ints.

  4. getKthDigit(n, k)
    Write the function getKthDigit(n, k) that takes a possibly-negative int n and a non-negative int k, and returns the kth digit of n, starting from 0, counting from the right. So:
       getKthDigit(789, 0) returns 9
       getKthDigit(789, 2) returns 7
       getKthDigit(789, 3) returns 0
       getKthDigit(-789, 0) returns 9

  5. setKthDigit(n, k, d)
    Write the function setKthDigit(n, k, d) that takes three integers -- n, k, and d -- where n is a possibly-negative int, k is a non-negative int, and d is a non-negative single digit (between 0 and 9 inclusive), and returns the number n but with the kth digit replaced with d. Counting starts at 0 and goes right-to-left, so the 0th digit is the rightmost digit. For example:
       setKthDigit(468, 0, 1) returns 461
       setKthDigit(468, 1, 1) returns 418
       setKthDigit(468, 2, 1) returns 168
       setKthDigit(468, 3, 1) returns 1468

  6. riverCruiseUpstreamTime(totalTime, totalDistance, riverCurrent)
    First, read the "River Cruise" example problem on this page. Then, write the function riverCruiseUpstreamTime(totalTime, totalDistance, riverCurrent) which takes three positive int or float values, the total time in hours of the roundtrip (up and back downstream), the total distance in km of the roundtrip, and the speed in km/hour of the river current. The function returns a float value of the time required to complete the upstream portion of the trip.