Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Exercise 2: Towers of Hanoi The Towers of Hanoi puzzle is legendary in Computer Science lore. It is one of the best examples of an

image text in transcribed
Exercise 2: Towers of Hanoi The Towers of Hanoi puzzle is legendary in Computer Science lore. It is one of the best examples of an efficient, intuitive recursive algorithm - and so, along with factorials, it is often one of the first learned. The idea is to move a stack of N discs from pile 1 to pile 3, following two rules: . Only one disc may be moved at a time; and . Larger discs cannot be placed on smaller discs. (Wikipedia) The optimal solution to the three-peg problem takes 2N-1 moves, for a stack of N discs. The recursive algorithm to move N discs from peg 1 to peg 3 is as follows: . Move N-1 discs from Peg 1 to Peg 2. . Move one disc from Peg 1 to Peg 3. . Move N-1 discs from Peg 2 to Peg 3. The beauty of the recursive solution is its simplicity. That's it. That's the whole algorithm. It simply calls itself in order to move the two smaller piles. If those have more than one disc, the algorithm splits the work again. Your program should print out directions to the user: "Move a disc from peg X to peg Y." You will need to create a function for this. Here is a suggested declaration: int towers(int numDiscs, int fromPile, int toPile, int tempPile): Please see me if you have any questions - recursion can be tricky! Please read the "discussion" section below Exercise 3, even if you don't do that one

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Mobile Communications

Authors: Jochen Schiller

2nd edition

978-0321123817, 321123816, 978-8131724262

More Books

Students also viewed these Programming questions