Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hackerrank -- Time taken for two squares to overlap

Tags:

math

Problem statement: Sherlock and Moving Tiles

TL;DR: Given 2 squares; with sides of length L, placed in an x-y plane, and both squares move along the line y=x (along the positive x and y) with velocities S1 and S2, what is the time taken at which the overlapping area of the two squares is equal to qi?

Hey, everyone.

Context: I am currently working on my Math skills after having taken some extensive time away from it. I think that it could improve the way I approach coding problems as well by recognising when a problem is Math-related. I'm going through Hackerrank & KhanAcademy for learning purposes at the moment.

Question: I am having trouble visualising the formula for the given problem. I have the answer and have also taken a peek at the editorial's answer but I still can't fully grasp it. Perhaps, I am forgetting something fundamental in my math knowledge. The problem's difficulty level is set as easy. So, I am a little embarrassed since I am having trouble solving a relatively easy Math problem. I hope that you won't hold that against me. :)

Anyway, the formula used to solve this problem is as follows:-

t = Math.sqrt(2) * (L - Math.sqrt(qi)) / Math.abs(S2-S1)

Could I get a breakdown/upwards derivation of the final formula? i.e. What do I need to think about in order to arrive at that formula? I understand parts of it but can't seem to pull them together into a conclusive answer.

Thanks for the help, guys. Any help is greatly appreciated!

like image 435
cottonman Avatar asked Sep 10 '25 22:09

cottonman


1 Answers

The area qi is half of the square of the diagonal of the square formed by the intersection of the two squares. We will only look at diagonals here because the squares are moving along y=x. We will therefore consider the top right corner of the square with the slower velocity (we do not need to check for this, this will be covered by using the absolute value of the denominator) which we'll call A and the bottom left corner of the faster square which we'll call B.

The distance x1 of A from the origin is d1 = s1*t + L*sqrt(2).

The distance x2 of B from the origin is d2 = s2*t.

We know that qi = [(x1 - x2)^2] / 2.

Substituting x1 and x2, (s1*t + L*sqrt(2) - s2*t)^2 = 2*qi.

On taking sqrt on both sides and solving for t, we end up with:

t = sqrt(2) * (sqrt(qi) - L) / (s1 - s2)

To make sure that both numerator and denominator are positive, take -1 common from both the numerator and denominator.

t = sqrt(2) * (L - sqrt(qi)) / (s2 - s1)

The assumption we have made here is that s1 < s2. To make this work for all cases, simply take the absolute value of their difference in the denominator.

like image 116
EvilTak Avatar answered Sep 13 '25 17:09

EvilTak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!