diff --git a/toh_solver.c b/toh_solver.c index 8cf5102..e1155e3 100644 --- a/toh_solver.c +++ b/toh_solver.c @@ -27,8 +27,19 @@ * @param target The rod to which the disk shall be moved. * @return True if the move was successful and according to the rules, false otherwise. */ -static bool ts_move_disk(Rod source, Rod target) { - return false; +static bool ts_move_disk(RodName source, RodName target) { + TohBoard board = tb_get_board(); + if (!tb_is_valid(board)) { + return false; + } + + Disk disk = tb_pop_disk(board, source); + + if (!td_is_valid(disk)) { + return false; + } + + return tb_push_disk(tb_get_board(), target, disk); } /** @@ -43,8 +54,39 @@ static bool ts_move_disk(Rod source, Rod target) { * @param target The rod to which the disks shall be moved. * @return True if the move was successful and according to the rules, false otherwise. */ -static bool ts_move_stack(unsigned short size, Rod source, Rod intermediate, Rod target) { - return false; +static bool ts_move_stack(unsigned short size, RodName source, RodName intermediate, RodName target) { + // inefficient implementation as it makes lots of unnecessary moves, if the number of disks is large + // but it's easier to implement + if (size == 1) { + return ts_move_disk(source, target); + } + + if (!ts_move_stack(size - 1, source, target, intermediate)) { + return false; + } + + if (!ts_move_disk(source, target)) { + return false; + } + + return ts_move_stack(size - 1, intermediate, source, target); +} + +static unsigned short ts_get_used_disks(RodName rod) { + TohBoard board = tb_get_board(); + if (!tb_is_valid(board)) { + return 0; + } + + unsigned short count = 0; + for (unsigned short i = 0; i < MAX_DISKS; i++) { + Disk disk = tb_get_disk(board, rod, i); + if (td_is_valid(disk)) { + count++; + } + } + + return count; } /* ========================================================= */ @@ -81,5 +123,10 @@ void ts_init(unsigned short disk_count) { * */ void ts_solve() { - return; + TohBoard board = tb_get_board(); + if (!tb_is_valid(board)) { + return; + } + + ts_move_stack(ts_get_used_disks(LEFT), LEFT, MIDDLE, RIGHT); } \ No newline at end of file