Skip to content

Instantly share code, notes, and snippets.

@kernelshreyak
Created June 4, 2019 08:22
Show Gist options
  • Save kernelshreyak/efa5a77951ee2cd402f13415a7b17642 to your computer and use it in GitHub Desktop.
Save kernelshreyak/efa5a77951ee2cd402f13415a7b17642 to your computer and use it in GitHub Desktop.
Tower of Hanoi solution implementation in PHP. Contents are also displayed
<?php
//Tower of Hanoi (n-disk) algorithm in PHP with Display of Pole Contents
//the 3 poles representation
$poles=array(array(),array(),array());
function TOH($n,$A="S",$B="I",$C="D"){
if($n>0){
TOH($n-1,$A,$C,$B);
echo "Move $A to $C \n";
move($A,$C);
dispPoles();
TOH($n-1,$B,$A,$C);
}
else{
return;
}
}
function initPoles($n){
global $poles;
for($i=$n;$i>=1;--$i){
$poles[0][]=$i;
}
}
function move($source,$destination){
global $poles;
//get source and destination pointers
if($source=="S") $ptr1=0;
elseif($source=="I") $ptr1=1;
else $ptr1=2;
if($destination=="S") $ptr2=0;
elseif($destination=="I") $ptr2=1;
else $ptr2=2;
$top=array_pop($poles[$ptr1]);
array_push($poles[$ptr2],$top);
}
function dispPoles(){
global $poles;
echo "S: [".implode(",",$poles[0])."] \n";
echo "I: [".implode(",",$poles[1])."] \n";
echo "D: [".implode(",",$poles[2])."] \n";
echo "\n\n";
}
$numdisks=5;
initPoles($numdisks);
echo "Tower of Hanoi Solution for $numdisks disks: \n\n";
dispPoles();
TOH($numdisks);
?>
@kernelshreyak
Copy link
Author

Sample output:
Tower of Hanoi Solution for 4 disks:

S: [4,3,2,1]
I: []
D: []

Move S to I
S: [4,3,2]
I: [1]
D: []

Move S to D
S: [4,3]
I: [1]
D: [2]

Move I to D
S: [4,3]
I: []
D: [2,1]

Move S to I
S: [4]
I: [3]
D: [2,1]

Move D to S
S: [4,1]
I: [3]
D: [2]

Move D to I
S: [4,1]
I: [3,2]
D: []

Move S to I
S: [4]
I: [3,2,1]
D: []

Move S to D
S: []
I: [3,2,1]
D: [4]

Move I to D
S: []
I: [3,2]
D: [4,1]

Move I to S
S: [2]
I: [3]
D: [4,1]

Move D to S
S: [2,1]
I: [3]
D: [4]

Move I to D
S: [2,1]
I: []
D: [4,3]

Move S to I
S: [2]
I: [1]
D: [4,3]

Move S to D
S: []
I: [1]
D: [4,3,2]

Move I to D
S: []
I: []
D: [4,3,2,1]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment