• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
ontheheap

Tower of Hanoi Recursively in c++ (long)

7 posts in this topic

Alright, so everything was going smooth with this book I'm reading (Data Structures for Game Programmers) until I got to the chapter on recursion. The first problem the author wants you to figure out is solving x to the nth power recursively. Alright, simple enough. I figured that one out pretty quickly, and thought that the next problem couldn't be any harder than that... Pseudo Code: (n = total blocks, s = start pole, d = dest pole, o = open pole)
Hanoi(n, s, d, o)
     if(n > 0)
        Hanoi(n-1, s, o d);
        Print "Moving n from s to d."
        Hanoi(n-1, o, d, s)
Example with calling Hanoi( 3, 1, 3, 2) prints out:
1    2   3
============
1  |   |   |
2  |   |   |   
3  |   |   |

Step 1: Moving 1 from 1 to 3.
1    2   3
============
   |   |   |
2  |   |   |   
3  |   | 1 |

Step 2: Moving 2 from 1 to 2.
1    2   3
============
   |   |   |
   |   |   |   
3  | 2 | 1 |

Step 3: Moving 1 from 3 to 2.
1    2   3
============
   |   |   |
   | 1 |   |   
3  | 2 |   |

Step 4: Moving 3 from 1 to 3.
1    2   3
============
   |   |   |
   | 1 |   |   
   | 2 | 3 |

Step 5: Moving 1 from 2 to 1.
1    2   3
============
   |   |   |
   |   |   |   
 1 | 2 | 3 |

Step 6: Moving 2 from 2 to 3. 
1    2   3
============
   |   |   |
   |   | 2 |   
 1 |   | 3 |

Step 7: Moving 1 from 1 to 3.
1    2   3
============
   |   | 1 |
   |   | 2 |   
   |   | 3 |

( 2^n - 1 moves)

35 minutes later, I'm still trying to figure out why the tower of hanoi recursive algorithm works. Basically, it looks like this:
void Hanoi(int numberOfBlocks, int startPole, int destPole, int openPole)
{
      if( numberOfBlocks > 0 )
      {
             // openPole and destPole are swapped
             Hanoi(numberOfBlocks - 1, startPole, openPole, destPole);

             cout << "Moving " << n << " from " << startPole;
             cout << " to " << destPole << endl;

             // openPole and startPole are swapped
             Hanoi(numberOfBlocks - 1, openPole, destPole, startPole);
      }
}



Alright, so I'll be passing in the total number of blocks to move, the starting pole those blocks are on, the final pole where they should end up, and the open pole. Lets say I have three blocks total, located on pole #1. I have a total of three poles, with #3 being the destination and #2 being the open pole. I want to move all 3 blocks to #3. So I call the Hanoi function like this:
Hanoi( 3, 1, 3, 2);



In the function, the if statement checks if numberOfBlocks is > 0, which it is, and then calls Hanoi again with numberOfBlocks - 1. The if statement gets checked again, and now numberOfBlocks = 2, so Hanoi is called again with numberOfBlocks - 1, and the if statement gets checked again seeing that numberOfBlocks now equals 1. Pretty simple recursion at this point. After the next call the function will start returning because the if statement will be false, and then cout will be called for the results of the second recursion (where n = 1). Then Hanoi is called again, until n = 0. Original call: ( 3, 1, 3, 2 ); // n, s, d, o 1. (2, 1, 2, 3 ); // n, s, o, d 2. (1, 1, 2, 3 ); 3. (0, 1, 2, 3 ); // if statement fails, function returns back to step 2 ------ And this is where I'm getting lost. After the third call's if statement fails, it returns back to step 2, where the first message is printed and Hanoi is called again. This time, the openPole and startPole values are swapped, so the call should look like this: 4. ( 1 (?), 2, 3, 1) // n, o, d, s At this point, what is the value of n that is passed into the function? At step 2, n = 2, so I'm assuming that the ? in step 4 should be 2-1, or just 1. Which starts the entire thing again because the if statement is true. So, after each time the second hanoi function is called, it goes through the first few steps again. At this point, short of writing out /every/ step on a few sheets of paper, I don't see how it actually moves the correct pieces in the correct order. I'm really close to just pulling out a pad of paper and writing down each and every function call and the values involved, but I'm hoping someone who already understands how this works can help me out a bit. I understand how recursion works, but I don't understand how and why this algorithm does what it does.
0

Share this post


Link to post
Share on other sites
The way I thought about this recursive problem is that the function is a guide on how to move a stack of blocks from one pole to another - as long as I know how to move a (n-1) sized stack, moving a n sized one is easy: move all blocks but the one furthest down ((n-1) block) to the open pole, then move the last block to the final pole, then move the stack back on top of it.
0

Share this post


Link to post
Share on other sites
Yea, I see what you mean. So:


1 2 3
=========== -> ========== => ==========
| | | | | | 1
| 1 | | 1 | | | 2
3 | 2 | | 2 | 3 | | 3


Which is

Moving n discs
---------------
"move the top n-1 blocks to pillar 2"
"move the nth block tp pillar 3"
"move the n-1 blocks to pillar 3"

And I understand that (well, its easy to follow because everything is being moved in "chunks").

Moving n-1 discs
----------------
"move the top n-2 block (for 3 blocks, this is block 1) to pillar 3"
"move the n-1 block (block 2) to pillar 2"
"move the n-2 block (block 1) from pillar 3 (step 1) to pillar 2"


Which is fine, it's just moving one block at a time instead of moving them in chunks.

And the function is doing this recursively:

1. moves the top n-1 discs from the starting pillar onto the open pillar
2. moves the nth disc from the starting pillar to the destination pillar
3. moves the top n-1 discs from the open pillar to the destination pillar

And I get that too.. but I don't get how it actually /works/ recursively!

I think I need to just write all of the steps down on a sheet of paper so I can follow the entire thing step by step.
0

Share this post


Link to post
Share on other sites
Ah i think you could do a bit better then that.


hanoi (board, goal, moveslist)
if board is = goal then return moveslist
make a list of all moves that are movable from board, and put them into l1
Evaluate how close each of them are to the goal state, and sort them by it. (so really close states come before other states, ect).
Make a new board B2
In order of how close they are to the goal state, counter x
Make b2, equal to board
Make the xth move on l1, on b2 (so you make the move that the xth element on l1 says, on b2)
call hanoi (b2, goal)
if hanoi returned a moveslist then
add the x'th element of b2 to the beginning of moveslist
return moveslist
end if
end order
Return falure


Now, figure out HOW it works, WHY it works, then from scratch make another ENTIRELY DIFFERENT one. Also figure out why yours DIDN"T work, what is WRONG with it, and use that to fix your version.

Also, try to make a recurcive version of a* to solve this problem.
Its pretty easy once you get around to it (its just another set of values to sort by, an extra argument for the function, and a bit of math (not much tho))

From,
Nice coder

[Edited by - Nice Coder on January 1, 2005 7:14:21 PM]
0

Share this post


Link to post
Share on other sites
to nice coder:
*bump*, what are you talking about?!

to onTheHeap:
the first time i saw this, i didn't post a reply because the way it works is so obvious that i couldn't even explain it. So i'll just repeat what you and Snaily said.

The recursive procedure is like follow:
(1) Hanoi(n, s, d, o)
(2) if(n > 0)
(3) Hanoi(n-1, s, o d);
(4) Print "Moving n from s to d."
(5) Hanoi(n-1, o, d, s)


(1) What does this procedure do: it moves the upper N blocks from S to D using O as temporary pillar.
(2) the condition: if n=0, it means no blocks must be moved, so do nothing
(3) move the upper N-1 blocks from here to the open pillar, where the destination pillar can for the moment be used as the temporary pillar.
(4) move the current block to D
(5) move the stack on the open pillar back to the destination pillar.

Ok, that's clear, you've already catched it, i'm just repeating what you already know.



So, why does it work? ...let's do a bit logic and you'll see.

First, let's proove it works for a single block (n=1) (*)
Hanoi (1, s, d, o) will work since:

Hanoi(0, s, o d); => this call will do nothing
Print "Moving n from s to d." => the block is moved as expected
Hanoi(0, o, d, s) => this call will do nothing


Now, let's assume it works also for n blocks! We'll now try to prove that it'll also work for n+1 blocks: (**)

Hanoi (n+1, s, d, o)
Hanoi(n, s, o d); => By hypothesis, it is meant to work correctly and moves the n upper blocks to the open pillar
Print "Moving n from s to d." => the block is moved to the destination
Hanoi(n-1, o, d, s) => By hypothesis, it is meant to work correctly and moves the n upper blocks back from the open pillar onto the destination pillar
=> Therefore, as we have proven, if it works for n blocks then it'll also work for n+1 blocks.

Now let's combine (*) and (**).
Since it works for 1 block, it'll also work for 2 blocks and since it works for 2 block, it'll also work for 3 blocks... and so on. I think you got it.

This may sound a bit complicated at first but in fact, it's incredibly simple.


But this is nearly a mathematical explanation. What is important to get is really being able to "think recursively", once you have your mind thinking this way, you'll see the incredible simplicity and power of recursiviness. Isn't the hanoi example an elegant and simple solution after all? Once you got it, you won't need explanations or proofs anymore, nor even think more than a minute to solve problems like these.


(PS: sometimes, i really wonder why i'm rated downwards (i'm good after all) and see people like nice coder telling bullshit have good ratings... idiot forums!)
0

Share this post


Link to post
Share on other sites
misterX, ratings++

I wrote a really simple app yesterday that pauses at each step and prints out a bit of information regarding the current values for each of the variables and what values the hanoi function was called with. Made it a lot easier to see just what exactly was going on.

The recursive solution to this problem is nothing short of astounding! This is the first real recursive problem I've looked at (other than the common fibonacci numbers, and x to the y power examples). Really cool stuff.
0

Share this post


Link to post
Share on other sites
Misterx: Oh. You hurt my feelings........ Mean.

And for the record: Thats psudocode for a recursive greedy search that i used to do the towers problem, until i found a*.

From,
Nice coder
0

Share this post


Link to post
Share on other sites

A non-recursive solution to this problem is as follows:
*on odd-numbered moves, move the smallest disk to the next peg (from 1 to 2, from 2 to 3 and from 3 to 1).
*on even-numbered moves, make the only possible move that does not involve the smallest disk.

Try it!

(if you get the final stack in the wrong place, try moving the smallest disk in the opposite direction: 1=>3, 2=>1, 3=>2)
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0