18 February 2022

Lots of angles this week

Task 1 - smallest path through triangle

At first I thought that this was like Chinese Checkers: the path could only descend to the nodes immediately to its left or right in the row below, but the examples imply that we are simply looking for the sum of the smallest values in each row.

Someone will surely come up with a 1-line answer to this, but I amused myself by finding a way to display the triangle in the output.  What I came up with was to put it in a string:

$example = qq[
    [1], 
   [5,3], 
  [2,3,4], 
 [7,1,0,2], 
[6,4,5,2,8] ]; 

which displays nicely, and then use eval to put it into an array of arrays:

$test = eval("[$example]");

from which the solution is pretty simple.

Task 2 - area covered by 2 rectangles

Mohammad and Colin like it when the task is slightly under-defined, but I took it that the area we are looking for is the area covered by one or both rectangles.  If the rectangles don't overlap then clearly it's just the sum of the two rectangles' areas, but if they do overlap we then have to subtract the overlapped area, as we've counted it twice.

There are a lot of possibilities for overlap, such as:


However, I came up with some rules which I think work with any pair:

Start by adding the areas of the two rectangles.  If they overlap then subtract the area of overlap, else don't.

But do they overlap?

Condition 1: The rectangles may overlap if the bottom of rect1 is below the top of rect2 and the top of rect1 is above the bottom of rect2.

Condition 2: They may also overlap if the right of rect1 is to the right of the left of rect2
and the left of rect1 is to the left of the right side of rect2.

They do overlap if condition 1 and condition 2 are both true.

So now we need the area of the overlap. The overlap area is bounded by: 
  • the greater of the bottoms,
  • the lesser of the tops, 
  • the leftmost of the rights and 
  • the rightmost of the lefts.
If that sounds complicated, apply it to the examples shown above and you'll see what I mean.

This works for 2 rectangles, but if there are 3 or more it gets harder, but I won't tell you how to do that in case it's next week's challenge.






No comments:

Post a Comment