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.2 There are three ants on different vertices of a triangle. What is <strong>the</strong> probability of collision<br />

(between any two or all of <strong>the</strong>m) if <strong>the</strong>y start walking on <strong>the</strong> sides of <strong>the</strong> triangle?<br />

SOLUTION<br />

Similarly find <strong>the</strong> probability of collision with ‘n’ ants on an ‘n’ vertex polygon.<br />

pg 68<br />

None of <strong>the</strong> three ants will collide if all three are moving in clockwise direction, or all three<br />

are moving in a counter-clockwise direction. O<strong>the</strong>rwise, <strong>the</strong>re will definitely be a collision.<br />

How many ways are <strong>the</strong>re for <strong>the</strong> three ants to move? Each ant can move in 2 directions, so<br />

<strong>the</strong>re are 2^3 ways <strong>the</strong> ant can move. There are only two ways which will avoid a collision,<br />

<strong>the</strong>refore <strong>the</strong> probability of collision is (2^3 – 2) / (2^3) = 6 / 8 = 3 / 4.<br />

To generalize this to an n-vertex polygon: <strong>the</strong>re are still only 2 ways in which <strong>the</strong> ants can<br />

move to avoid a collision, but <strong>the</strong>re are 2^n ways <strong>the</strong>y can move total. Therefore, in general,<br />

probability of collision is (2^n – 2) / 2^n = 1 – 1/2^(n-1).<br />

CareerCup.com<br />

1 8 8

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

Saved successfully!

Ooh no, something went wrong!