Functions
WebDev/*nix assorted functions & hacks
Search
find all
Array
-
Bash
-
Classes
-
Config
-
DateTime
-
Debug
-
dotjs
-
File
-
foooo
-
Git
-
HTML
-
Images
-
Javascript
-
Linux
-
Math
-
Misc
-
MySQL
-
OS X
-
Reading
-
Redis
-
Shell scripts
-
snippets
-
SQL
-
Strings
-
TextMate
-
Web
-
\(^o^)/ Fun!
-
_Misc hacks
-
_Pages
\(^o^)/ Fun!
* Readme
Alphanumeric images to ascii
Conway's Game of Life as TextMate command
Langton's Ant
Quine
Sierpiński Carpet
Sierpiński Triangle
Towers of Hanoi
8
found
auth
Name:
Category: \(^o^)/ Fun!
Body:
<?php /* PHP implementation of Towers Of Hanoi by M. Spreij <mac.com@nemo>, 02-10-2004 The Towers of Hanoi is a classic game, involving three pegs and a number of discs. The discs are stacked on the first peg ordered by size (largest at the bottom), and the challenge is to move them to another (usually the third) peg with the least possible moves, abiding by the rules: - you can move only 1 disc at the time - a disc may not be placed on a smaller disc It's a bit of a rough version, not optimized or anything fancy and using some unusual variables, but hey, it was a quick hack, after 4 AM :-) Background: http://en.wikipedia.org/wiki/Tower_of_Hanoi http://mathworld.wolfram.com/TowerofHanoi.html ..and a few hundred other pages, Google 'm :-) */ $me = basename($_SERVER['PHP_SELF']); $discs = abs((int) $_POST['discs']); $img = 'data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs='; // black pixel # -- Form ------------------------- echo " <H2>Towers of Hanoi</H2> <FORM ACTION='$me' METHOD='post'>"; if (! $discs) { echo "Enter the number of discs to use (try something *below* 10 the first time) and hit go:<BR>"; }else{ echo "Try again?<BR>"; } echo " <INPUT TYPE='text' NAME='discs' SIZE='3' MAXLENGTH='3' VALUE='$discs'> <INPUT TYPE='submit' VALUE='Go'></FORM>"; # --------------------------------- # 'Pegs' $A = range($discs, 1); $B = array(); $C = array(); $moves = 0; if ($discs) { echo $discs ." discs:<BR>"; move(); # draws the starting positions place('A', 'C', count($A)); echo "This took ". ($moves - 1) ." moves."; } # place($from, $to, $num) function place($from, $to, $num) { global $count, $A, $B, $C; $between = implode(array_diff(array('A', 'B', 'C'), array($from, $to))); if ($num > 1) { place($from, $between, $num-1); }else{ move($from, $to); return true; } move($from, $to); place($between, $to, $num-1); } # move($from = '', $to = '') function move($from = '', $to = '') { global $A, $B, $C, $moves, $discs; if ($from && $to) array_push($$to, array_pop($$from)); # meh $moves++; echo "<TABLE BORDER='1'><TR>"; foreach(array($A, $B, $C) as $stack) { echo "<TD WIDTH='". $discs*4 ."' VALIGN='bottom' ALIGN='center'> <BR>"; draw_stack($stack); echo '</TD>'; } echo "</TR></TABLE>"; } # draw_stack($stack) function draw_stack($stack) { global $img; $stack = array_reverse($stack); foreach($stack as $disc) { echo "<IMG SRC='$img' WIDTH='".($disc*4)."' HEIGHT='4' BORDER='0'><BR>"; } } echo '<HR>Done';
Footer