mirror of
https://github.com/TheAlgorithms/Java.git
synced 2026-03-13 08:40:43 +08:00
Add Tower of Hanoi recursive algorithm (#7235)
* Add Tower of Hanoi recursive algorithm with tests * Fix SpotBugs issues and format TowerOfHanoi tests * Enhance existing TowerOfHanoi and remove duplicate recursion version * Fix clang-format issue --------- Co-authored-by: Deniz Altunkapan <deniz.altunkapan@outlook.com>
This commit is contained in:
committed by
GitHub
parent
8403b8feb1
commit
0c79d33eb5
@@ -1,14 +1,31 @@
|
||||
package com.thealgorithms.puzzlesandgames;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
public class TowerOfHanoiTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("diskCountAndMoveCount")
|
||||
void testMoveCountMatchesFormula(int disks, int expectedMoves) {
|
||||
List<String> result = new ArrayList<>();
|
||||
TowerOfHanoi.shift(disks, "A", "B", "C", result);
|
||||
assertEquals(expectedMoves, result.size());
|
||||
}
|
||||
|
||||
private static Stream<Arguments> diskCountAndMoveCount() {
|
||||
return Stream.of(Arguments.of(1, 1), Arguments.of(2, 3), Arguments.of(3, 7), Arguments.of(4, 15), Arguments.of(5, 31), Arguments.of(10, 1023));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHanoiWithOneDisc() {
|
||||
List<String> result = new ArrayList<>();
|
||||
@@ -39,6 +56,15 @@ public class TowerOfHanoiTest {
|
||||
assertEquals(expected, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHanoiWithDifferentPoles() {
|
||||
List<String> result = new ArrayList<>();
|
||||
TowerOfHanoi.shift(2, "X", "Y", "Z", result);
|
||||
|
||||
List<String> expected = List.of("Move 1 from X to Y", "Move 2 from X to Z", "Move 1 from Y to Z");
|
||||
assertEquals(expected, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHanoiWithZeroDiscs() {
|
||||
List<String> result = new ArrayList<>();
|
||||
@@ -47,4 +73,10 @@ public class TowerOfHanoiTest {
|
||||
// There should be no moves if there are 0 discs
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHanoiWithNegativeDiscsThrows() {
|
||||
List<String> result = new ArrayList<>();
|
||||
assertThrows(IllegalArgumentException.class, () -> TowerOfHanoi.shift(-1, "Pole1", "Pole2", "Pole3", result));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user