CMU 15-112: Fundamentals of Programming and Computer Science
Writing-Session1 Practice



  1. distance(x1, y1, x2, y2)
    Write the function distance(x1, y1, x2, y2) that takes four int or float values x1, y1, x2, y2 that represent the two points (x1, y1) and (x2, y2), and returns the distance between those points as a float.

  2. circlesIntersect(x1, y1, r1, x2, y2, r2)
    Write the function circlesIntersect(x1, y1, r1, x2, y2, r2) that takes 6 numbers (ints or floats) -- x1, y1, r1, x2, y2, r2 -- that describe the circle centered at (x1,y1) with radius r1, and the circle centered at (x2,y2) with radius r2, and returns True if the two circles intersect and False otherwise.

  3. getInRange(x, bound1, bound2)
    Write the function getInRange(x, bound1, bound2) which takes 3 int or float values -- x, bound1, and bound2, where bound1 is not necessarily less than bound2. If x is between the two bounds, just return it unmodified. Otherwise, if x is less than the lower bound, return the lower bound, or if x is greater than the upper bound, return the upper bound. For example:
    • getInRange(1, 3, 5) returns 3 (the lower bound, since 1 lies to the left of the range [3,5])
    • getInRange(4, 3, 5) returns 4 (the original value, since 4 is in the range [3,5])
    • getInRange(6, 3, 5) returns 5 (the upper bound, since 6 lies to the right of the range [3,5])
    • getInRange(6, 5, 3) also returns 5 (the upper bound, since 6 lies to the right of the range [3,5])

  4. isFactor(f, n)
    Write the function isFactor(f, n) that takes two int values f and n, and returns True if f is a factor of n, and False otherwise. Note that every integer is a factor of 0.

  5. 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) == 9 getKthDigit(789, 1) == 8 getKthDigit(789, 2) == 7 getKthDigit(789, 3) == 0 getKthDigit(-789, 0) == 9

  6. 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). This function returns the number n 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) == 461 setKthDigit(468, 1, 1) == 418 setKthDigit(468, 2, 1) == 168 setKthDigit(468, 3, 1) == 1468