Advent of PBT 2021 β Learn how to use property based testing and fast-check through examples
Our algorithm today is: racePodium.
It comes with the following documentation and prototype:
type RaceParticipants = [number, number, number, number, number];
/**
* 25 Horses Puzzle
* > Letβs say that you have 25 horses, and you want to pick the
* > fastest 3 horses out of those 25. In each race, only 5
* > horses can run at the same time because there are only 5
* > tracks. What is the minimum number of races required to find
* > the 3 fastest horses without using a stopwatch?
*
* Find the podium!
* See https://matt-croak.medium.com/google-interview-25-horses-c982d0a9b3af for more details.
*
* @param runRace - Run a race with the received participants.
* Outputs the final ranking. In case of equality the participant
* with the smallest id wins.
*
* @returns
* Ordered top three.
*/
export function racePodium(
runRace: (...participants: RaceParticipants) => RaceParticipants
): [number, number, number]
More details on this subject at: https://matt-croak.medium.com/google-interview-25-horses-c982d0a9b3af
We already wrote some examples based tests for it:
it("should find the right podium for a given race", () => {
// Arrange
const speeds = [
14, 1, 8, 19, 23,
13, 17, 10, 3, 5,
2, 21, 22, 9, 11,
20, 7, 16, 24, 18,
0, 15, 12, 6, 4
];
const compareParticipants = (pa: number, pb: number) => {
if (speeds[pa] !== speeds[pb]) return speeds[pb] - speeds[pa];
else return pa - pb;
};
const runRace = (...participants: RaceParticipants): RaceParticipants => {
return participants.sort(compareParticipants);
};
// Act
const podium = racePodium(runRace);
// Assert
expect(podium).toEqual([18, 4, 12]);
});
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-15-xvst7?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-15-solution-5ako
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)