25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Solutions to Chapter 7 | Object Oriented Design<br />

7 6 Implement a jigsaw puzzle Design <strong>the</strong> data structures and explain an algorithm to<br />

solve <strong>the</strong> puzzle<br />

SOLUTION<br />

1 5 9<br />

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

pg 62<br />

1 class Edge {<br />

2 enum Type { inner, outer, flat }<br />

3 Piece parent;<br />

4 Type type;<br />

5 bool fitsWith(Edge type) { ... }; // Inners & outer fit toge<strong>the</strong>r.<br />

6 }<br />

7 class Piece {<br />

8 Edge left, right, top, bottom;<br />

9 Orientation solvedOrientation = ...; // 90, 180, etc<br />

10 }<br />

11 class Puzzle {<br />

12 Piece[][] pieces; /* Remaining pieces left to put away. */<br />

13 Piece[][] solution;<br />

14 Edge[] inners, outers, flats;<br />

15 /* We’re going to solve this by working our way in-wards, starting<br />

16 * with <strong>the</strong> corners. This is a list of <strong>the</strong> inside edges. */<br />

17 Edge[] exposed_edges;<br />

18<br />

19 void sort() {<br />

20 /* Iterate through all edges, adding each to inners, outers,<br />

21 * etc, as appropriate. Look for <strong>the</strong> corners—add those to<br />

22 * solution. Add each non-flat edge of <strong>the</strong> corner to<br />

23 * exposed_edges. */<br />

24 }<br />

25<br />

26 void solve() {<br />

27 foreach edge1 in exposed_edges {<br />

28 /* Look for a match to edge1 */<br />

29 if (edge1.type == Edge.Type.inner) {<br />

30 foreach edge2 in outers {<br />

31 if edge1.fitsWith(edge2) {<br />

32 /* We found a match! Remove edge1 from<br />

33 * exposed_edges. Add edge2’s piece to<br />

34 * solution. Check which edges of edge2 are<br />

35 * exposed, and add those to exposed_edges. */<br />

36 }<br />

37 }<br />

38 /* Do <strong>the</strong> same thing, swapping inner & outer. */<br />

39 }<br />

40 }

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

Saved successfully!

Ooh no, something went wrong!