--- title: Towers of Hanoi id: 5951ed8945deab770972ae56 challengeType: 5 forumTopicId: 302341 localeTitle: Башни Ханоя --- ## Description
Задача:

Решите проблему Башни Ханоя .

Ваше решение должно принять количество дисков в качестве первых параметров и три строки, используемые для идентификации каждого из трех стеков дисков, например towerOfHanoi(4, 'A', 'B', 'C') . Функция должна возвращать массив массивов, содержащий список ходов, source -> destination. Например, массив [['A', 'C'], ['B', 'A']] указывает, что 1-й ход состоял в том, чтобы переместить диск из стека A в C, а второй шаг состоял в том, чтобы переместить диск из стека B в A.

## Instructions
## Tests
```yml tests: - text: towerOfHanoi is a function. testString: assert(typeof towerOfHanoi === 'function'); - text: towerOfHanoi(3, ...) should return 7 moves. testString: assert(res3.length === 7); - text: towerOfHanoi(3, 'A', 'B', 'C') should return [['A','B'], ['A','C'], ['B','C'], ['A','B'], ['C','A'], ['C','B'], ['A','B']]. testString: assert.deepEqual(towerOfHanoi(3, 'A', 'B', 'C'), res3Moves); - text: towerOfHanoi(5, "X", "Y", "Z") 10th move should be Y -> X. testString: assert.deepEqual(res5[9], ['Y', 'X']); - text: towerOfHanoi(7, 'A', 'B', 'C') first ten moves are [['A','B'], ['A','C'], ['B','C'], ['A','B'], ['C','A'], ['C','B'], ['A','B'], ['A','C'], ['B','C'], ['B','A']] testString: assert.deepEqual(towerOfHanoi(7, 'A', 'B', 'C').slice(0, 10), res7First10Moves); ```
## Challenge Seed
```js function towerOfHanoi(n, a, b, c) { // Good luck! return [[]]; } ```
### After Tests
```js const res3 = towerOfHanoi(3, 'A', 'B', 'C'); const res3Moves = [['A', 'B'], ['A', 'C'], ['B', 'C'], ['A', 'B'], ['C', 'A'], ['C', 'B'], ['A', 'B']]; const res5 = towerOfHanoi(5, 'X', 'Y', 'Z'); const res7First10Moves = [['A', 'B'], ['A', 'C'], ['B', 'C'], ['A', 'B'], ['C', 'A'], ['C', 'B'], ['A', 'B'], ['A', 'C'], ['B', 'C'], ['B', 'A']]; ```
## Solution
```js function towerOfHanoi(n, a, b, c) { const res = []; towerOfHanoiHelper(n, a, c, b, res); return res; } function towerOfHanoiHelper(n, a, b, c, res) { if (n > 0) { towerOfHanoiHelper(n - 1, a, c, b, res); res.push([a, c]); towerOfHanoiHelper(n - 1, b, a, c, res); } } ```