PHP5 REQUIRED
<pre><?php class HanoiStack { public function HanoiStack() { } public function pushItem( $intItem ) { { } else { if ( $intItem > $this->getLastItem() ) { throw new Exception( 'Cannot put bigger brick on smaller (' . $intItem . ' on ' . $this->getLastItem() . ')' ); } } } public function popItem() { { throw new Exception( 'Cannot pop intem from empty stack' ); } } public function getLastItem() { { return -1; } } public function __toString() { $s = '[ '; foreach ( $this->arrStack as $v ) { $s .= $v . ' '; } $s .= \"]n\"; return $s; } } class Hanoi { private $intN; private $intMoves; public function Hanoi( $intN ) { for ( $i = 0; $i < 3; $i++ ) { $this->arrStacks[ $i ] = new HanoiStack(); } for ( $i = $this->intN - 1; $i >= 0; $i-- ) { $this->arrStacks[ 0 ]->pushItem( $i ); } } public function solve() { $this->printTowers(); // z wiezy 0 na wieze 2 if ( $this->intN <= 0 ) { throw new Exception( 'Wrong intN' ); } $intBrickOnePosition = 0; $intMoveDirection = ( $this->intN % 2 === 1 ) ? -1 : 1; for ( $i = 0; $i < $i_max; $i++ ) { if ( $i % 2 === 0 ) { // zdejmij jedynke (tu zero: indeksujemy klocki od zera) $intItem = $this->arrStacks[ $intBrickOnePosition ]->popItem(); print( '(' . $intBrickOnePosition . ')--[ ' . $intItem . ' ]-->(' . ( $intBrickOnePosition + $intMoveDirection + 3 ) % 3 . ')' . \"n\" ); $intBrickOnePosition = ( $intBrickOnePosition + $intMoveDirection + 3 ) % 3; // i przenies ja w keirunku $intMoveDirection $this->arrStacks[ $intBrickOnePosition ]->pushItem( $intItem ); } else { $x = 0; // znajdz wieze z min i max brickiem !== 1 for ( $j = 0; $j < 3; $j++ ) { if ( $j !== $intBrickOnePosition ) { $arrTowerIndices[ $x ] = $j; $arrTopItems[ $x ] = $this->arrStacks[ $j ]->getLastItem(); $x++; } } $intTowerWithSmallerTopItem = ( $arrTopItems[ 0 ] < $arrTopItems[ 1 ] ) ? $arrTowerIndices[ 0 ] : $arrTowerIndices[ 1 ]; $intTowerWithBiggerTopItem = ( $arrTopItems[ 0 ] > $arrTopItems[ 1 ] ) ? $arrTowerIndices[ 0 ] : $arrTowerIndices[ 1 ]; if ( $this->arrStacks[ $intTowerWithSmallerTopItem ]->getLastItem() === -1 ) { // zamien je to ta pierwsza jest pusta $temp = $intTowerWithSmallerTopItem; $intTowerWithSmallerTopItem = $intTowerWithBiggerTopItem; $intTowerWithBiggerTopItem = $temp; } // przenies klocek $intItem = $this->arrStacks[ $intTowerWithSmallerTopItem ]->popItem(); print( '(' . $intTowerWithSmallerTopItem . ')--[ ' . $intItem . ' ]-->(' . $intTowerWithBiggerTopItem . ')' . \"n\" ); $this->arrStacks[ $intTowerWithBiggerTopItem ]->pushItem( $intItem ); } $this->printTowers(); } } private function printTowers() { } } class HanoiTowers { { try { $objHanoiTower = new Hanoi( 3 ); $objHanoiTower->solve(); } catch ( Exception $e ) { } } } HanoiTowers::main(); ?></pre>