DEV Community

Simon Green
Simon Green

Posted on

Triangles and rectangles

Weekly Challenge 152

The challenge, My solution

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
Enter fullscreen mode Exit fullscreen mode

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:

  1. Take the first eight things that look like an integer from the command line.
  2. Create rect1 with the first four numbers.
  3. Create rect2 with the next four numbers.
  4. Set area to be the area of the two rectangles, ignoring any overlap.
  5. Calculate the overlap. The bottom left will be the maximum of x1 and y1 of the two rectangles. The top right will be the minimum of x2 and y2.
  6. If there is an overlap (x1 < x2 and y1 < y2), create another rectangle object and subtract its area from step 4.
  7. 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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)