Iterative Solution to the hanruata Problem

Source: Internet
Author: User

Let's take a look at the recursive solution. It takes less than a minute to complete using the Perl language.

Sub hanno_recursive {
My ($ from, $ to, $ reserve, $ n) = @_;
If (1 = $ n ){
Print "move $ n from $ from to $ to \ n ";
Return;
}

Hanno_recursive ($ from, $ reserve, $ to, $ n-1 );
Print "move $ n from $ from to $ to \ n ";
Hanno_recursive ($ reserve, $ to, $ from, $ n-1 );
}

Extremely concise and elegant. It fully embodies the elegance of recursion.


Next, consider the iterative solution. Consider breaking down the problem into a tree structure. Obviously, when a B c is regarded as a circle, the left and right Subtrees have some symmetry. That is, clockwise or counterclockwise rotation.

In this way, we can use the left tree to obtain the right tree. The problem becomes linear recursion, which is easy to convert to iteration.

Now that you know the principle, it takes a lot of effort to write this code. It took an hour to adjust it.

Sub hanno_iterate {
My ($ from, $ to, $ reserve, $ n) = @_;
My @ left = ();
My @ right = ();
# Move to leaf node
My $ COUNT = $ N;
While ($ count> 1 ){
My $ TMP = $;
$ To = $ reserve;
$ Reserve = $ TMP;
$ Count --;
}

For (my $ Index = 1; $ index <= $ N; $ index ++ ){
My $ new = "move $ index from $ from to $ to \ n ";

Push @ left, $ new;
While ($ new = shift @ right ){
Push @ left, $ new;
}
Last if ($ Index = $ N );

If ($ index % 2) ==( $ n % 2 )){
# Anti-CLOCK $ from-> $ to, $ reserve-> $ from, $ to-> $ reserve
Foreach my $ OPT (@ left ){
My $ left_value = "$ Opt ";
$ Left_value = ~ TR/ABC/CAB /;
Push @ right, $ left_value;
}
} Else {
# CLOCK $ from-> $ reserve, $ reserve-> $ to, $ to-> $ from
Foreach my $ OPT (@ left ){
My $ left_value = "$ Opt ";
$ Left_value = ~ TR/ABC/BCA /;
Push @ right, $ left_value;
}
}
My $ TMP = $;
$ To = $ reserve;
$ Reserve = $ TMP;
}

Foreach my $ OPT (@ left ){
Print $ OPT;
}


}


Iterative Solution to the hanruata Problem

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.