27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

<strong>Solutions</strong> 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 />

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 />

»»<br />

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

to intersect.<br />

»»<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 />

»»<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 />

»»<br />

When possible, design <strong>and</strong> use data structures. It shows that you underst<strong>and</strong> <strong>and</strong> care<br />

about object oriented design.<br />

»»<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 <strong>and</strong> explain your choice.<br />

»»<br />

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

» » Underst<strong>and</strong> limitations of floating point representations. Never check for equality with<br />

==.<br />

1 8 9<br />

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

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

Saved successfully!

Ooh no, something went wrong!