Project Euler Solutions by Ross Marks

<?php
/*****************************
 * ProjectEuler - Problem 28
 * By Ross Marks
 *****************************
 * Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
 * 
 * 21 22 23 24 25
 * 20  7  8  9 10
 * 19  6  1  2 11
 * 18  5  4  3 12
 * 17 16 15 14 13
 * 
 * It can be verified that the sum of the numbers on the diagonals is 101.
 * 
 * What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?
 ****************************/
define('DOWN'0);
define('LEFT'3);
define('RIGHT'1);
define('UP'2);

$gridsize 1001;
$direction RIGHT;
$total 0;

$grid = array();
$dimension $gridsize $gridsize;
$y $x round($gridsize 2);

/*
$grid[0] = [1,3,6,5,2];
$grid[1] = [1,'',2,'',2];
$grid[2] = [1,'',2,'',2];
$grid[3] = [1,'',2,'',2];
$grid[4] = [1,2,2,2,2];
*/

// create empty grid
for($i 0$i $gridsize$i++){
  for (
$j 0$j $gridsize$j++){
    
$grid[$i][$j] = '';
  }
}

// populate grid
$remain $distance 1;
$number 1;
for ( 
$count 0$count $dimension$count++ ){
  
$grid[$x][$y] = $number;

  switch ( 
$direction ){
    case 
LEFT$y--; break;
    case 
UP$x--; break;
    case 
DOWN$x++; break;
    case 
RIGHT$y++; break;
  }

  if ( --
$remain == ){
    switch ( 
$direction ){
      case 
DOWN:
        
$direction LEFT;
        
$distance++;

        break;
      case 
UP:
        
$distance++;

      default:
        
$direction--;

        break;
    }
    
$remain $distance;
  }
    
$number++;
  
}

// work out first diagnol
for($i 1$i <= $gridsize$i++){
  
$total bcadd($total$grid[$i][$i]);
}
// work out second diagnol
$y $gridsize;
for(
$i 1$i <= $gridsize$i++){
  
$total bcadd($total$grid[$i][$y]);
  
$y--;
}
// remove center as added twice
$y $x round($gridsize 2);
$total bcsub($total$grid[$y][$x]);

echo 
"Awnser: $total";

/***
 * Below not used, was for dev
 */

//display
//for($i = 0; $i < $gridsize; $i++){
//  for ($j = 0; $j < $gridsize; $j++){
//    echo " ".$grid[$i][$j]." ";
//  }
//  echo "\n";
//}
//print_r($grid);

//echo (check_grid() ? "true":"false");
/*
function check_grid(){
  global $grid, $gridsize;
  $size = 0;

  // check top
  foreach($grid[1] as $checkme)
    if($checkme)
      $size++;
  // check left
  for($i = 1; $i <= $gridsize; $i++)
    if($grid[$i][1])
      $size++;
  // check bottom
  foreach($grid[$gridsize] as $checkme)
    if($checkme)
      $size++;
  // check right
  for($i = 1; $i <= $gridsize; $i++)
    if($grid[$i][$gridsize-1])
      $size++;
  
  if($size < ($gridsize*3))
    return false;
  return true;
}
*/
?>