Simulate the solution for the Tower of Hanoi puzzle. Your type should take the number of rings as input an return an array of steps to move the rings from tower A to tower B using tower C as additional. Each entry in the array should be a pair of strings `[From, To]` which denotes ring being moved `From -> To`. Learn array type operations in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement a Hanoi type that simulates the Tower of Hanoi puzzle, producing the complete sequence of moves needed to transfer all rings from one tower to another.
Simulate the solution for the Tower of Hanoi puzzle. Your type should take the number of rings as input an return an array of steps to move the rings from tower A to tower B using tower C as additional. Each entry in the array should be a pair of strings [From, To] which denotes ring being moved From -> To.
Change the following code to make the test cases pass (no type check errors).
type Hanoi<
N extends number,
From = 'A',
To = 'B',
Intermediate = 'C',
Count extends unknown[] = []
> = Count['length'] extends N
? []
: [
...Hanoi<N, From, Intermediate, To, [unknown, ...Count]>,
[From, To],
...Hanoi<N, Intermediate, To, From, [unknown, ...Count]>,
]How it works:
N, the source tower From, the destination tower To, and the auxiliary tower Intermediate.Count tuple acts as a depth counter. Each recursive call adds one element to Count, effectively reducing the problem size by one ring at each level of recursion.Count['length'] extends N (we have recursed N levels deep), we return an empty array as the base case -- there are no rings left to move.N-1 rings from From to Intermediate (using To as the auxiliary). Then move the bottom ring directly from From to To as [From, To]. Finally, recursively move the N-1 rings from Intermediate to To (using From as the auxiliary).... concatenates all the move arrays together into a single flat sequence of [From, To] pairs.This challenge helps you understand recursive type-level algorithms and tuple concatenation and how to apply these concepts in real-world scenarios.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount