proud Posted May 27, 2009 Share Posted May 27, 2009 This code below solves the towers of hanoi problem which is an old chinese game that consists of the following rules: There are three towers T1 T2 T3 on a platform and n>0 disks (D1…….Dn) of different diameters placed on the first tower T1. The disks are in the order of decreasing diameter as one scans up the tower T1.Monks were reputedly supposed to move the disks from tower T1 to tower T3 obeying the following rules 1.only one disk can be moved at a time 2. no disk can be placed on top of another disk with a smaller diameter 3. to complete the task, the disk should be stacked on tower T3exactly like they are on tower at1. http://javaboutique.internet.com/Tower/ (You can try the game on this site to understand it) <?php function hanoi($plates, $from, $to) { while($plates > 0) { $using = 6 - ($from + $to); hanoi(--$plates, $from, $using); ////////line 5/////// print "Move plate from $from to $to<br>"; $from = $using; } } //Arguments: No of plates, From stick(1,2 or 3), To stick(1,2 or 3; except From stick) hanoi(3, 1, 3); ?> All I want is an explanation of the logic behind the code,specially line 5... because I tried hard but couldn't figure it out! Link to comment https://forums.phpfreaks.com/topic/159900-towers-of-hanoi-problem/ Share on other sites More sharing options...
cunoodle2 Posted May 27, 2009 Share Posted May 27, 2009 Its a recursive function that is calling itself. That is one of the better ways to solve an issue like this is through recursion. I'll break line 5 down here.. hanoi(--$plates, $from, $using); hanoi: This is the name of the function. It is essentially just calling itself. ( ): Everything enclosed between "(" and ")" are variables that are being passed to the function --$plates: This decreasing the variable "--$plates" by one and sending it to the function $from: passing the value of the "$from" variable $using: passing the value of the "$using" variable Link to comment https://forums.phpfreaks.com/topic/159900-towers-of-hanoi-problem/#findComment-843400 Share on other sites More sharing options...
proud Posted May 27, 2009 Author Share Posted May 27, 2009 Okay, this explains a big part of the program mystery, so a last question would be: Why did we use the variable $using: $using=6 - ($from + $to)? what part of the problem does it solve? Link to comment https://forums.phpfreaks.com/topic/159900-towers-of-hanoi-problem/#findComment-843410 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.