Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,27 @@ describe('hanoiTower', () => {

expect(moveCallback).toHaveBeenCalledTimes((2 ** numberOfDiscs) - 1);
});
it('should solve tower of hanoi puzzle with 0 discs', () => {
const moveCallback = jest.fn();

hanoiTower({
numberOfDiscs: 0,
moveCallback,
});

expect(moveCallback).not.toHaveBeenCalled();
});

it('should solve tower of hanoi puzzle with negative number of discs', () => {
const moveCallback = jest.fn();

expect(() => {
hanoiTower({
numberOfDiscs: -3,
moveCallback,
});
}).not.toThrow();

expect(moveCallback).not.toHaveBeenCalled();
});
});
7 changes: 7 additions & 0 deletions src/algorithms/uncategorized/hanoi-tower/hanoiTower.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,13 @@ export default function hanoiTower({
// that might contain elements (discs). Each disc is represented as a number.
// Larger discs have bigger number equivalent.

// If there are no discs to move then the puzzle is already solved.
// This also guards the recursion from infinitely calling itself
// in case if numberOfDiscs is zero or negative.
if (numberOfDiscs <= 0) {
return;
}

// Let's create the discs and put them to the fromPole.
for (let discSize = numberOfDiscs; discSize > 0; discSize -= 1) {
fromPole.push(discSize);
Expand Down