25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Solutions to Chapter 10 | Ma<strong>the</strong>matical<br />

10 5 Given two squares on a two dimensional plane, find a line that would cut <strong>the</strong>se two<br />

squares in half<br />

SOLUTION<br />

CareerCup com<br />

pg 68<br />

Any line that goes through <strong>the</strong> center of a rectangle must cut it in half Therefore, if you drew<br />

a line connecting <strong>the</strong> centers of <strong>the</strong> two squares, it would cut both in half<br />

1 public class Square {<br />

2 public double left;<br />

3 public double top;<br />

4 public double bottom;<br />

5 public double right;<br />

6 public Square(double left, double top, double size) {<br />

7 this.left = left;<br />

8 this.top = top;<br />

9 this.bottom = top + size;<br />

10 this.right = left + size;<br />

11 }<br />

12<br />

13 public Point middle() {<br />

14 return new Point((this.left + this.right) / 2,<br />

15 (this.top + this.bottom) / 2);<br />

16 }<br />

17<br />

18 public Line cut(Square o<strong>the</strong>r) {<br />

19 Point middle_s = this.middle();<br />

20 Point middle_t = o<strong>the</strong>r.middle();<br />

21 if (middle_s == middle_t) {<br />

22 return new Line(new Point(left, top),<br />

23 new Point(right, bottom));<br />

24 } else {<br />

25 return new Line(middle_s, middle_t);<br />

26 }<br />

27 }<br />

28 }<br />

SUGGESTIONS AND OBSERVATIONS<br />

The main point of this problem is to see how careful you are about coding It’s easy to glance<br />

over <strong>the</strong> special cases (e g , <strong>the</strong> two squares having <strong>the</strong> same middle) Make a list of <strong>the</strong>se<br />

special cases before you start <strong>the</strong> problem and make sure to handle <strong>the</strong>m appropriately<br />

1 9 2

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!