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 3 Given two lines on a Cartesian plane, determine whe<strong>the</strong>r <strong>the</strong> two lines would intersect<br />

SOLUTION<br />

1 8 9<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Concepts and Algorithms<br />

pg 68<br />

There are a lot of unknowns in this problem (what format are <strong>the</strong> lines in? What if <strong>the</strong>y are <strong>the</strong><br />

same line?), but let’s assume:<br />

» If two lines are <strong>the</strong> same (same line = same slope and y-intercept), <strong>the</strong>y are considered<br />

to intersect<br />

» We get to decide <strong>the</strong> data structure<br />

1 public class Line {<br />

2 static double epsilon = 0.000001;<br />

3 public double slope;<br />

4 public double yintercept;<br />

5<br />

6 public Line(double s, double y) {<br />

7 slope = s;<br />

8 yintercept = y;<br />

9 }<br />

10<br />

11 public boolean intersect(Line line2) {<br />

12 return Math.abs(slope - line2.slope) > epsilon ||<br />

13 Math.abs(yintercept - line2.yintercept) < epsilon;<br />

14 }<br />

15 }<br />

OBSERVATIONS AND SUGGESTIONS:<br />

» Ask questions This question has a lot of unknowns—ask questions to clarify <strong>the</strong>m Many<br />

interviewers intentionally ask vague questions to see if you’ll clarify your assumptions<br />

» When possible, design and use data structures It shows that you understand and care<br />

about object oriented design<br />

» Think through which data structures you design to represent a line There are a lot of<br />

options, with lots of trade offs Pick one and explain your choice<br />

» Don’t assume that <strong>the</strong> slope and y-intercept are integers<br />

» Understand limitations of floating point representations Never check for equality with<br />

==

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

Saved successfully!

Ooh no, something went wrong!