Reputation: 15
I'm not necessarily looking for code to solve this problem but more how to figure out the logic behind it.
I'm doing a homework problem for a Computer Science class I'm taking and one of the problems states, "Method isUntangled that accepts two parameters: a circle’s diameter and a square’s side length, both of type double. It returns true if and only if the circle and square do not intersect when their centers are aligned"
This is the image provided to help with understanding: Image
I have tried to just simply return True if the diameter is less than the squares side length or return True if the side length of the square is less than the diameter of the circle. Looking back at it now I see why it didn't work.
I'm more seeing if someone could explain the logic/math that could be used to figure this problem out.
Thank You
Upvotes: 1
Views: 606
Reputation: 426
there is 2 ways to understand logic
so, in this both case circle & square are tangent between those 2 state (same in both cases).
Upvotes: 1
Reputation: 580
The equation of a circle is x^2 + y^2 = r^2
You only need to work out if one of the square's lines collides with the circle to see any if them collide since they're aligned in the center. The equation of a line is x = c
where c
is a constant. You can substitute the value of x or y into the circle equation. For example, for x = 2
:
2^2 + y^2 = r^2 => 4 + y^2 = r^2
r
is given to you too, so substitute that in r = 1 => 4 + y^2 = 1^2 = 1
=> y^2 = -3
Hence, since there's no (real) square root of -3
, they don't collide.
If the circle is sufficiently big enough, relative to the square, there will be a real solution to the last part. Our equation of a line that represents the square's side should actually be constrained since the squares straight lines don't go on forever, they stop at x = y = +- square_length/2
. So check if y(from equation) < y(square_height)
(or x
and width
, they're the same). So essentially, there are 2 cases you need to check. You can turn that into code.
Upvotes: 0
Reputation: 2317
return diameter > length && diameter / 2 < length / Math.sqrt(2)
First condition checks that circle not inside the square and second condition checks that square not inside the circle
Upvotes: 0
Reputation: 13123
With the centers aligned, there are three cases:
'3' applies if the diameter of the circle is less than one-half the square length.
'1' applies if the diameter of the circle is greater than the distance from the square center to a square corner. that's half the length of the square's diagonal.
'2' applies in all other cases.
Upvotes: 0