[RESOLVED] Algo needed: Spiral of numbers based on _n_
Hi,
I'm trying to solve this one assignment we have in PHP.
Based on the given number n, the script is supposed to print out a n*n grid of numbers following the pattern in this image:
http://img222.imageshack.us/img222/4623/79890400.png
In this example the given number n is 4.
Would any of you have an idea for a good algorithm?
I couldn't come up with a "good" algorithm, just a more-or-less brute force approach:
PHP Code:
<?php
function spiral ( $n )
{
$n = abs ((int) $n );
$result = array();
$count = 0 ;
for( $i = 1 ; $i <= $n ; $i ++) {
if( $i % 2 ) {
for( $y = $i , $x = 1 ; $x <= $i ; $x ++) {
$result [ $x ][ $y ] = ++ $count ;
}
for( $x = $i , $y = $i - 1 ; $y >= 1 ; $y --) {
$result [ $x ][ $y ] = ++ $count ;
}
}
else {
for( $y = 1 , $x = $i ; $y <= $i ; $y ++) {
$result [ $x ][ $y ] = ++ $count ;
}
for( $x = $i - 1 , $y = $i ; $x >= 1 ; $x --) {
$result [ $x ][ $y ] = ++ $count ;
}
}
}
return $result ;
}
?>
<html><head><title>Test</title>
<style type='text/css'>
table {
border-collapse: collapse;
border: solid 2px black;
}
td {
text-align: center;
padding: 0.2em;
border: solid 1px black;
}
</style></head><body>
<?php
$test = range ( 1 , 6 );
foreach( $test as $num ) {
echo "<h3>Test Value: $num </h3>\n" ;
$data = spiral ( $num );
echo "<table>\n" ;
for( $y = 1 ; $y <= $num ; $y ++) {
echo "<tr>" ;
for( $x = 1 ; $x <= $num ; $x ++) {
echo "<td>" . $data [ $x ][ $y ]. "</td>" ;
}
echo "</tr>\n" ;
}
echo "<table>\n" ;
}
?>
</body></html>
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in
Nation
eBookworm.us
Thank you NogDog, the solution is Perfect!!
Great job!
Happy holidays!
// Rade
Thread Information
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Tags for this Thread
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Bookmarks