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

22 public double slope;<br />

23 public double intercept;<br />

24 private boolean infinite_slope = false;<br />

25 public Line(GraphPoint p, GraphPoint q) {<br />

26 if (Math.abs(p.x - q.x) > epsilon) { // if x’s are different<br />

27 slope = (p.y - q.y) / (p.x - q.x); // compute slope<br />

28 intercept = p.y - slope * p.x; // y intercept from y=mx+b<br />

29 } else {<br />

30 infinite_slope = true;<br />

31 intercept = p.x; // x-intercept, since slope is infinite<br />

32 }<br />

33 }<br />

34<br />

35 public boolean isEqual(double a, double b) {<br />

36 return (Math.abs(a - b) < epsilon);<br />

37 }<br />

38<br />

39 @Override<br />

40 public int hashCode() {<br />

41 int sl = (int)(slope * 1000);<br />

42 int in = (int)(intercept * 1000);<br />

43 return sl | in;<br />

44 }<br />

45<br />

46 @Override<br />

47 public boolean equals(Object o) {<br />

48 Line l = (Line) o;<br />

49 if (isEqual(l.slope, slope) && isEqual(l.intercept, intercept)<br />

50 && (infinite_slope == l.infinite_slope)) {<br />

51 return true;<br />

52 }<br />

53 return false;<br />

54 }<br />

55 }<br />

OBSERVATIONS AND SUGGESTIONS<br />

»»<br />

Be careful about <strong>the</strong> calculation of <strong>the</strong> slope of a line. The line might be completely<br />

vertical. We can keep track of this in a separate flag (infinite_slope). We need to check<br />

this condition in <strong>the</strong> equals method.<br />

» » Remember that when we perform division to calculate <strong>the</strong> slope, division is not exact.<br />

Therefore, ra<strong>the</strong>r than checking to see if two slopes are exactly equal, we need to check<br />

if <strong>the</strong>y’re different by greater than epsilon.<br />

CareerCup.com<br />

1 9 4

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

Saved successfully!

Ooh no, something went wrong!