CMU 15-112: Fundamentals of Programming and Computer Science
Homework 1 (Due Sat 6-Feb at 8pm ET (Pittsburgh-time))
Important Note: Do not start this homework until you have first carefully read the 112 syllabus and submitted the 112 Student Contract!
- This homework is solo. You must not collaborate with anyone (besides current course TA's and faculty) in any way. See the syllabus for more details.
- To start:
- Create a folder named 'week1'
- Download both hw1.py and cs112_s21_week1_linter.py to that folder
- Edit hw1.py using VSCode
- When you have completed and fully tested hw1, submit hw1.py to Autolab. For this hw, you may submit up to 10 times (which is more than you should require), but only your last submission counts.
- Do not use string indexing, loops, lists, list indexing, or recursion this week.
- Do not hardcode the test cases in your solutions.
- Hint: The starter hw1.py file includes test functions.
You may comment out individual test functions in
testAll()
to temporarily bypass those tests. The autograder will run all the tests in any case. Ask a TA if you need help with this.
Homework1 overview:
- Part 0 Friday Lab [10 pts]
Attend Friday lab (in your assigned recitation time). To receive full credit, you must show up on time, stay the whole time, be focused and uni-tasking (not multi-tasking), and fully participating. - Part 1 Standard or Spicy [50 pts]
Either do the (smaller) part1-standard problems or the (larger, somewhat more challenging) part1-spicy problem (below), your choice.- Part 1 Standard [50 pts]
- fabricYards(inches) [10 pts]
- fabricExcess(inches) [10 pts]
- nearestBusStop(street) [10 pts]
- numberOfPoolBalls(rows) [10 pts]
- numberOfPoolBallRows(balls) [10 pts]
- Part 1 Spicy [50 pts]
- playThreeDiceYahtzee(dice) [50 pts]
- Part 1 Standard [50 pts]
- Part 2 Required [40 pts]
Everyone must do these problems. We suggest completing part1 before attempting part2. - Part 3 Bonus/Optional [up to 2 bonus pts]
These are bonus/optional. They are fun, interesting problems that are worth very few points. If you attempt these, do them for the fun and the learning, not the points.- colorBlender(rgb1, rgb2, midpoints, n) [1 bonus pt]
- findIntRootsOfCubic(a,b,c,d) [1 bonus pt]
Standard Problems
Either do the (smaller) part1-standard problems or the (larger, somewhat more challenging) part1-spicy problem (below), your choice, but not both.
- fabricYards(inches) [standard, 10 pts]
Fabric must be purchased in whole yards, so purchasing just 1 inch of fabric requires purchasing 1 entire yard. With this in mind, write the function fabricYards(inches) that takes the number of inches of fabric desired, and returns the smallest number of whole yards of fabric that must be purchased. Note: 36 inches equals 1 yard. - fabricExcess(inches) [standard, 10 pts]
Write the function fabricExcess(inches) that takes the number of inches of fabric desired and returns the minimum number of inches of excess fabric that must be purchased (as purchases must be in whole yards). Hint: you may want to use fabricYards, which you just wrote! - nearestBusStop(street) [standard, 10 pts]
Write the function nearestBusStop(street) that takes a non-negative int street number, and returns the nearest bus stop to the given street, where buses stop every 8th street, including street 0, and ties go to the lower street, so the nearest bus stop to 12th street is 8th street, and the nearest bus stop to 13 street is 16th street. The function returns an integer, so for example, nearestBusStop(5) returns 8. - numberOfPoolBalls(rows) [standard, 10 pts]
Pool balls are arranged in rows where the first row contains 1 pool ball and each row contains 1 more pool ball than the previous row. Thus, for example, 3 rows contain 6 total pool balls (1+2+3). With this in mind, write the function numberOfPoolBalls(rows) that takes a non-negative int value, the number of rows, and returns another int value, the number of pool balls in that number of full rows. For example, numberOfPoolBalls(3) returns 6. We will not limit our analysis to a "rack" of 15 balls. Rather, our pool table can contain an unlimited number of rows. Hint: you may want to briefly read about Triangular Numbers. Also, remember not to use loops! - numberOfPoolBallRows(balls) [standard, 10 pts]
This problem is the inverse of the previous problem. Write the function numberOfPoolBallRows(balls) that takes a non-negative int number of pool balls, and returns the smallest int number of rows required for the given number of pool balls. Thus, numberOfPoolBallRows(6) returns 3. Note that if any balls must be in a row, then you count that row, and so numberOfPoolBallRows(7) returns 4 (since the 4th row must have a single ball in it). Hint: you may want to briefly read about Triangular Numbers, and also think about how this problem relates to the numberOfPoolBalls problem above.
Spicy Problem
You should either do all the standard problems (above) or this spicy problem, but not both.
- playThreeDiceYahtzee(dice) [spicy, 50 pts]
In this exercise, we will write a simplified form of the dice game Yahtzee. In this version, the goal is to get 3 matching dice, and if you can't do that, then you hope to at least get 2 matching dice. The game is played like so:- Roll 3 dice.
- If you do not have 3 matching dice:
- If you have 2 matching dice (a pair), keep the pair and roll one die to replace the third die.
- Otherwise, if you have no matching dice, keep the highest die and roll two dice to replace the other two dice.
- Repeat step 2 one more time.
- Finally, compute your score like so:
- If you have 3 matching dice, your score is 20 + the sum of the matching dice.
- So if you have 4-4-4, your score is 20+4+4+4, or 32.
- If you only have 2 matching dice, your score is 10 + the sum of the matching dice.
- So if you have 4-4-3, your score is 10+4+4, or 18.
- If you have no matching dice, your score is the highest die.
- So if you have 4-3-2, your score is just 4.
- If you have 3 matching dice, your score is 20 + the sum of the matching dice.
Also note: we will represent a hand of 3 dice as a single 3-digit integer. So the hand 4-3-2 will be represented by the integer 432. With that, let's start writing some code. Be sure to write your functions in the same order as given here, since later functions will make use of earlier ones!
- handToDice(hand)
Write the (very short) function handToRolls(hand) that takes a hand, which is a 3-digit integer, and returns 3 values, each of the 3 dice in the hand. For example:
Hint: You might find // and % useful here, and also getKthDigit.assert(handToDice(123) == (1,2,3)) assert(handToDice(214) == (2,1,4)) assert(handToDice(422) == (4,2,2))
Another hint: This returns a tuple. You cannot use tuple indexing this week, but you can use tuple assignment, like so:def f(m): return (m+1,m+2,m+3) x,y,z = f(4) # this does tuple assignment! print(f'After tuple assignment, x={x}, y={y}, z={z}')
- diceToOrderedHand(a, b, c)
Write the function diceToOrderedHand(a, b, c) that takes 3 dice and returns them in a hand, which is a 3-digit integer. However, even if the dice are unordered, the resulting hand must be ordered so that the largest die is on the left and smallest die is on the right. For example:
Hint: You can use max(a,b,c) to find the largest of 3 values, and min(a,b,c) to find the smallest.assert(diceToOrderedHand(1,2,3) == 321) assert(diceToOrderedHand(6,5,4) == 654) assert(diceToOrderedHand(1,4,2) == 421) assert(diceToOrderedHand(6,5,6) == 665) assert(diceToOrderedHand(2,2,2) == 222)
- playStep2(hand, dice)
This is the most complicated part. Write the function playStep2(hand, dice) that plays step 2 as explained above. This function takes a hand, which is a 3-digit integer, and it also takes dice, which is an integer containing all the future rolls of the dice. For example, if dice is 5341, then the next roll will be a 1, then the roll after that will be a 4, then a 3, and finally a 5. Note that in a more realistic version of this game, instead of hard-coding the dice in this way, we'd probably use a random-number generator.
With that, the function plays step2 of the given hand, using the given dice to get the next rolls as needed. At the end, the function returns the new hand, but it has to be ordered, and the function also returns the resulting dice (which no longer contain the rolls that were just used).
For example:
Here, the hand is 413, and the future dice rolls are 2312. What happens? Well, there are no matching dice in 413, so we keep the highest die, which is a 4, and we replace the 1 and the 3 with new rolls. Since new rolls come from the right (the one's digit), those are 2 and 1. So the new hand is 421. It has to be sorted, but it already is. Finally, the dice was 2312, but we used 2 digits, so now it's just 23. We return the hand and the dice, so we return (421, 23).assert(playStep2(413, 2312) == (421, 23))
Here are some more examples. Be sure you carefully understand them:
Hint: You may wish to use handToDice(hand) at the start to convert the hand into the 3 individual dice.assert(playStep2(413, 2345) == (544, 23)) assert(playStep2(544, 23) == (443, 2)) assert(playStep2(544, 456) == (644, 45))
Hint: Then, you may wish to use diceToOrderedHand(a, b, c) at the end to convert the 3 dice back into a sorted hand.
Hint: Also, remember to use % to get the one's digit, and use //= to get rid of the one's digit. - score(hand)
Almost there... Now write the function score(hand) that takes a 3-digit integer hand, and returns the score for that hand as explained in step4 above. For example:
Hint: The structure of this function is actually quite similar to the previous function.assert(score(432) == 4) assert(score(532) == 5) assert(score(443) == 10+4+4) assert(score(633) == 10+3+3) assert(score(333) == 20+3+3+3) assert(score(555) == 20+5+5+5)
- playThreeDiceYahtzee(dice)
Ok, we've made it to the last function: playThreeDiceYahtzee(dice), the function that actually earns the points! This function takes one value, the dice with all the rolls for a game of 3-Dice Yahtzee. The function plays the game -- it does step1 and gets the first 3 dice (from the right), then it does step2 twice (by calling playStep2, which you already wrote), and then it computes the score (by calling score, which you already wrote). The function should return two values -- the resulting hand and the score for that hand. For example:assert(playThreeDiceYahtzee(2312413) == (432, 4)) assert(playThreeDiceYahtzee(2315413) == (532, 5)) assert(playThreeDiceYahtzee(2345413) == (443, 18)) assert(playThreeDiceYahtzee(2633413) == (633, 16)) assert(playThreeDiceYahtzee(2333413) == (333, 29)) assert(playThreeDiceYahtzee(2333555) == (555, 35))
Required Problems
Everyone must do all these required problems.
- rectanglesOverlap(left1, top1, width1, height1, left2, top2, width2, height2) [required, 10 pts]
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 (so we say that "up is down"). - threeLinesArea(m1, b1, m2, b2, m3, b3) [required, 30 pts]
Write the function threeLinesArea(m1, b1, m2, b2, m3, b3) that takes six int or float values representing the 3 lines:
y = m1*x + b1
y = m2*x + b2
y = m3*x + b3
First find where each pair of lines intersects, then return the area of the triangle formed by connecting these three points of intersection. If no such triangle exists (if any two of the lines are parallel), return 0. To do this, use three helper functions: one to find where two lines intersect (which you will call three times), a second to find the distance between two points, and a third to find the area of a triangle given its side lengths. Hint: you may want to briefly read about Heron's Formula.
Bonus Problems
Bonus problems are entirely optional and worth few points. Do them for the fun and the learning.
- bonus: colorBlender(rgb1, rgb2, midpoints, n) [bonus, 1 pt]
This problem implements a color blender, inspired by this tool. In particular, we will use it with integer RGB values (it also does hex values and RGB% values, but we will not use those modes). Note that RGB values contain 3 integers, each between 0 and 255, representing the amount of red, green, and blue respectively in the given color, where 255 is "entirely on" and 0 is "entirely off".
For example, consider this case. Here, we are combining crimson (rgb(220, 20, 60)) and mint (rgb(189, 252, 201)), using 3 midpoints, to produce this palette (using our own numbering convention for the colors, starting from 0, as the tool does not number them):
There are 5 colors in the palette because the first color is crimson, the last color is mint, and the middle 3 colors are equally spaced between them.color0: rgb(220, 20, 60) color1: rgb(212, 78, 95) color2: rgb(205, 136, 131) color3: rgb(197, 194, 166) color4: rgb(189, 252, 201)
So we could ask: if we start with crimson and go to mint, with 3 midpoints, what is color #1? The answer then would be rgb(212, 78, 95).
One last step: we need to represent these RGB values as a single integer. To do that, we'll use the first 3 digits for red, the next 3 for green, the last 3 for blue, all in base 10 (decimal, as you are accustomed to). Hence, we'll represent crimson as the integer 220020060, and mint as the integer 189252201.
With all that in mind, write the function colorBlender(rgb1, rgb2, midpoints, n), which takes two integers representing colors encoded as just described, a non-negative integer number of midpoints, and a non-negative integer n, and returns the nth color in the palette that the tool creates between those two colors with that many midpoints. If n is out of range (too small or too large), return None.
For example, following the case above: colorBlender(220020060, 189252201, 3, 1) returns 212078095
Hints: RGB values must be ints, not floats. Also, remember to use roundHalfUp(n) instead of round(n) when calculating midpoint colors. - bonus: findIntRootsOfCubic(a,b,c,d) [bonus, 1 pt]
Write the function findIntRootsOfCubic(a,b,c,d) that takes the int or float coefficients a, b, c, d of a cubic equation of this form:
y = ax3 + bx2 + cx + d
You are guaranteed the function has 3 real roots, and in fact that the roots are all integers. Your function should return these 3 roots in increasing order. How does a function return multiple values? Like so:
To get started, you'll want to read about Cardano's cubic formula here. Then, from that page, use this formula:return root1, root2, root3
x = {q + [q2 + (r-p2)3]1/2}1/3 + {q - [q2 + (r-p2)3]1/2}1/3 + p where:
p = -b/(3a), q = p3 + (bc-3ad)/(6a2), r = c/(3a)
This isn't quite as simple as it seems, because your solution for x will not only be approximate (and not exactly an int, so you'll have to do something about that), but it may not even be real! Though the solution is real, the intermediate steps may include some complex values, and in these cases the solution will include a (possibly-negligibly-small) imaginary value. So you'll have to convert from complex to real (try c.real if c is complex), and then convert from real to int.
Great, now you have one root. What about the others? Well, we can divide the one root out and that will leave us with a quadratic equation, which of course is easily solved. A brief, clear explanation of this step is provided here. Don't forget to convert these to int values, too!
So now you have all three int roots. Great job! All that's left is to sort them. Now, if this were later in the course, you could put them in a list and call a built-in function that will sort for you. But it's not, so you can't. Instead, figure out how to sort these values using the limited built-in functions and arithmetic available this week. Then just return these 3 values and you're done.