#30430Medium

Tower of hanoi

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.

Challenge Instructions: Tower of hanoi

Medium

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.

Wikipedia GeeksForGeeks

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
type Tests = [
  Expect<Equal<Hanoi<0>, []>>,
  Expect<Equal<Hanoi<1>, [['A', 'B']]>>,
  Expect<Equal<Hanoi<2>, [['A', 'C'], ['A', 'B'], ['C', 'B']]>>,
  Expect<
    Equal<
      Hanoi<3>,
      [
        ['A', 'B'],
        ['A', 'C'],
        ['B', 'C'],
        ['A', 'B'],
        ['C', 'A'],
        ['C', 'B'],
        ['A', 'B'],
      ]
    >
  >,
  Expect<
    Equal<
      Hanoi<5>,
      [
        ['A', 'B'],
        ['A', 'C'],
        ['B', 'C'],
        ['A', 'B'],
        ['C', 'A'],
        ['C', 'B'],
        ['A', 'B'],
        ['A', 'C'],
        ['B', 'C'],
        ['B', 'A'],

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

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:

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.

Share this challenge