Advent of PBT 2021 — Learn how to use property based testing and fast-check through examples
Our algorithm today is: nonogramSolver.
It comes with the following documentation and prototype:
/**
* Solver of nonograms.
*
* Nonogram is a game in which the user is asked to colorize a grid
* based on hints. A cell in the grid will be either filled or not.
*
* For instance, the grid below:
*
* 12
* 3211
*
* 1 2 ????
* 1 1 ????
* 3 ????
* 1 1 ????
*
* Will result in:
*
* 12
* 3211
*
* 1 2 x.xx
* 1 1 x..x
* 3 xxx.
* 1 1 .x.x
*
* To define this grid you'll have to pass:
* - rows: [[1,2],[1,1],[3],[1,1]]
* - columns: [[3],[2],[1,1],[2,1]]
*
* @param rows - For each row, the set of hints concerning the
* number of filled cells
* @param columns - For each column, the set of hints concerning
* the number of filled cells
*/
declare function nonogramSolver(
rows: number[][],
columns: number[][]
): string;
We already wrote some examples based tests for it:
it("should be able to solve our nonogram", () => {
// Arrange
const rows = [[1, 2], [1, 1], [3], [1, 1]];
const columns = [[3], [2], [1, 1], [2, 1]];
let expectedSolution = "";
expectedSolution += "x.xx\n";
expectedSolution += "x..x\n";
expectedSolution += "xxx.\n";
expectedSolution += ".x.x";
// Act
const solution = nonogramSolver(rows, columns);
// Assert
expect(solution).toEqual(expectedSolution);
});
it("should be able to solve nonogram with non unique solution", () => {
// Arrange
const rows = [[1], [1]];
const columns = [[1], [1]];
let expectedSolutionA = "";
expectedSolutionA += ".x\n";
expectedSolutionA += "x.";
let expectedSolutionB = "";
expectedSolutionB += "x.\n";
expectedSolutionB += ".x";
// Act
const solution = nonogramSolver(rows, columns);
// Assert
const isA = solution === expectedSolutionA;
const isB = solution === expectedSolutionB;
expect(isA || isB).toBe(true);
});
How would you cover it with Property Based Tests?
In order to ease your task we provide you with an already setup CodeSandbox, with examples based tests already written and a possible implementation of the algorithm: https://codesandbox.io/s/advent-of-pbt-day-13-r03cn?file=/src/index.spec.ts&previewwindow=tests
You wanna see the solution? Here is the set of properties I came with to cover today's algorithm: https://dev.to/dubzzz/advent-of-pbt-2021-day-13-solution-3bhn
Back to "Advent of PBT 2021" to see topics covered during the other days and their solutions.
More about this serie on @ndubien or with the hashtag #AdventOfPBT.
Top comments (0)