/    Sign up×
Community /Pin to ProfileBookmark

[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:
[URL=http://img222.imageshack.us/i/79890400.png/][IMG]http://img222.imageshack.us/img222/4623/79890400.png[/IMG][/URL]

In this example the given number n is 4.

Would any of you have an idea for a good algorithm?

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@NogDogDec 23.2010 — I couldn't come up with a "good" algorithm, just a more-or-less brute force approach:
[code=php]
<?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>
[/code]
Copy linkTweet thisAlerts:
@radeauthorDec 24.2010 — Thank you NogDog, the solution is Perfect!!

Great job! ?

Happy holidays!

// Rade
×

Success!

Help @rade spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...