Add a server for solving the hanoi puzzle

This commit is contained in:
Manuel Thalmann 2022-10-11 14:24:59 +02:00
parent f6fe871d80
commit 7ffda12287

View file

@ -0,0 +1,25 @@
package ch.nuth.zhaw.exbox;
/**
* Provides the functionality to determine the solution of a hanoi puzzle.
*/
public class HanoiServer implements CommandExecutor {
@Override
public String execute(String command) throws Exception {
int count = Integer.parseInt(command);
return moveDisks(count, 'A', 'B', 'C');
}
public String moveDisks(int count, char sourcePole, char restPole, char destinationPole) {
String start = "";
String mid = String.format("Move disk %d from %s to %s", count, sourcePole, destinationPole);
String end = "";
if (count > 1) {
start = moveDisks(count - 1, sourcePole, destinationPole, restPole);
end = moveDisks(count - 1, restPole, sourcePole, destinationPole);
}
return String.join(System.lineSeparator(), start, mid, end).trim();
}
}