DEV Community

Simon Green
Simon Green

Posted on

2 2

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay