Weekly Challenge 152
TASK #1 › Triangle Sum Path
Task
You are given a triangle array.
Write a script to find the minimum sum path from top to bottom.
My solution
This one appear to be quick and easy. Take the input and using the json module (JSON in Perl) turn it into an array of arrays. Then sum up the lowest number in each row, and display the result.
Examples
$ ./ch-1.py "[ [1], [5,3], [2,3,4], [7,1,0,2], [6,4,5,2,8] ]"
8
$ ./ch-1.py "[ [5], [2,3], [4,1,5], [0,1,2,3], [7,2,4,1,9] ]"
9
TASK #2 › Rectangle Area
Task
You are given coordinates bottom-left and top-right corner of two rectangles in a 2D plane.
Write a script to find the total area covered by the two rectangles.
My solution
Originally I thought this challenge was impossible, as two intersecting rectangles could have any shape intersecting it. But then realized from the examples that we were only talking about rectangles that aren't tilted.
For this task, I create a class (package in Perl) to represent a rectangle. It makes sure that x1 and y1 represents the bottom left and x2 and y2 represents the top right. It also has an area method that returns the area of the rectangle.
With that part done, the rest of the code works like this:
- Take the first eight things that look like an integer from the command line.
- Create rect1with the first four numbers.
- Create rect2with the next four numbers.
- Set areato be the area of the two rectangles, ignoring any overlap.
- Calculate the overlap. The bottom left will be the maximum of x1andy1of the two rectangles. The top right will be the minimum ofx2andy2.
- If there is an overlap (x1 < x2andy1 < y2), create another rectangle object and subtract its area from step 4.
- Print the number.
Examples
$ ./ch-2.py "(-1,0), (2,2) (0,-1), (4,4)"
22
$ ./ch-2.py "(-3,-1), (1,3) (-1,-3), (2,2)"
25
 

 
    
Top comments (0)