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 12 | Testing<br />

12.3 We have <strong>the</strong> following method used in a chess game: boolean canMoveTo(int x, int y)<br />

x <strong>and</strong> y are <strong>the</strong> coordinates of <strong>the</strong> chess board <strong>and</strong> it returns whe<strong>the</strong>r or not <strong>the</strong> piece<br />

can move to that position. Explain how you would test this method.<br />

SOLUTION<br />

There are two primary types of testing we should do:<br />

Validation of input/output:<br />

pg 70<br />

We should validate both <strong>the</strong> input <strong>and</strong> output to make sure that each are valid. This might<br />

entail:<br />

1. Checking whe<strong>the</strong>r input is within <strong>the</strong> board limit.<br />

»»<br />

Attempt to pass in negative numbers<br />

»»<br />

Attempt to pass in x which is larger than <strong>the</strong> width<br />

»»<br />

Attempt to pass in y which is larger than <strong>the</strong> width<br />

Depending on <strong>the</strong> implementation, <strong>the</strong>se should ei<strong>the</strong>r return false or throw an exception.<br />

2. Checking if output is within <strong>the</strong> valid set of return values. (Not an issue in this case,<br />

since <strong>the</strong>re are no “invalid” boolean values.)<br />

Functional testing:<br />

Ideally, we would like to test every possible board, but this is far too big. We can do a reasonable<br />

coverage of boards however. There are 6 pieces in chess, so we need to do something<br />

like this:<br />

1 foreach piece a:<br />

2 for each o<strong>the</strong>r type of piece b (6 types + empty space)<br />

3 foreach direction d<br />

4 Create a board with piece a.<br />

5 Place piece b in direction d.<br />

6 Try to move – check return value.<br />

2 1 1<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!