JavaScript recursive function solution "Hanoi"

Source: Internet
Author: User

"Hanoi" is a famous puzzle game. There are 3 pillars on the tower and a set of hollow discs with different diameters. At the beginning, all the discs on the pillars are stacked in order from small to large. The goal is to move a disk to another pillar each time, eventually moving a pile of discs to the target column, the process is not allowed to place the big big disk on the smaller disk.

Read this paragraph carefully, if there are 10 discs or more, the operation of the steps is absolutely shocking, but the goal is to move a pile of disk to the target column, if the above 9 disk as a set, the 10th disk as another set, first move 9 discs to another pillar, and then the above 8 disks as a set, The 9th disc is considered another set of ... And so on, the idea of the recursive function is reflected in the decomposition and movement.

Complete the code, very simple wording, do not know if there is a simpler wording?

var function {disc, begin, end, helper) {    if (Disc > 0) {        -1, begin, helper, end);        Document.writeln (' move disk ' + Disc + ' from ' + Begin + ' to ' + helper ')        ; -1, end, begin, helper);}    ; Hanoi (3, ' Pillar One ', ' Pillar II ', ' pillar Three ');

Output when the number of discs is 3:

Move 1 from pillar one to pillar three
Move 2 from pillar one to pillar two
Move 1 from pillar three to pillar two
Move 3 from pillar one to pillar three
Move 1 from pillar two to pillar one
Move 2 from pillar two to pillar three
Move 1 from pillar one to pillar three

The parameters passed to the Hanoi function include the currently moving disc number and the 3 pillars it will use. When it calls a veteran, it handles the disk on top of the disk currently being processed. Eventually, it will be called with a non-existent disk number. In such a case, it does nothing. Because the function ignores illegal values, there is no need to worry about causing a dead loop.

JavaScript recursive function solution "Hanoi"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.