ClarkeRubber

UNSW ProgComp: Problem 5 - 2006

Jun 9th, 2012
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.87 KB | None | 0 0
  1. <?php
  2.  
  3. $input = <<<END
  4. 5
  5.  1  9 12 20 23
  6. 17 25  3  6 14
  7.  8 11 19 22  5
  8. 24  2 10 13 16
  9. 15 18 21  4  7
  10. END;
  11.  
  12. function remove_empty($a){
  13.     if($a){
  14.         return true;
  15.     }
  16. }
  17.  
  18. $input = explode("\n", $input);
  19. array_shift($input); //remove the first line
  20. foreach($input as $key => $value){
  21.     $input[$key] = explode(" ", $value);
  22. }
  23.  
  24. foreach($input as $key => $value){
  25.     $input[$key] = array_filter($input[$key], "remove_empty");
  26.     $input[$key] = array_values($input[$key]);
  27. }
  28.  
  29. //var_dump($input);
  30. $numbers = array();
  31.  
  32. foreach($input as $key => $value){
  33.     foreach($value as $number){
  34.         if(in_array($number, $numbers)) die("Invalid data: missing or repeated number");
  35.         $numbers[] = $number;
  36.     }
  37. }
  38.  
  39. sort($numbers);
  40. //var_dump($numbers);
  41.  
  42. $last = 0;
  43. for($x = 0; $x < count($numbers); $x++){
  44.     if($numbers[$x] == $numbers[$x+1]) die("Invalid data: missing or repeated number");
  45. }
  46.  
  47. //now actually test if each collum and row adds up
  48. $sum = array();
  49. $sum['diag1'] = 0;
  50. $sum['diag2'] = 0;
  51.  
  52. for($x = 0; $x < count($input[0]); $x++){
  53.     $sum['col'][$x] = 0;
  54.     for($y = 0; $y < count($input); $y++){
  55.         //$input[$y][$y] and we are moving down the collum
  56.         $sum['col'][$x] += $input[$x][$y]; //add up in each collum, php should be alright with $sum[n] not having a preset value
  57.     }
  58. }
  59.  
  60. for($y = 0; $y < count($input); $y++){
  61.     $sum['row'][$y] = 0;
  62.     for($x = 0; $x < count($input[0]); $x++){
  63.         $sum['row'][$y] += $input[$x][$y];
  64.     }
  65. }
  66.  
  67. for($z = 0; $z < count($input); $z++){
  68.     $sum['diag1'] += $input[$z][$z];
  69.     $sum['diag2'] += $input[$z][count($input)-$z-1];
  70. }
  71.  
  72. //var_dump($sum);
  73.  
  74. if($sum['diag1'] != $sum['diag2']) die("Invalid data: inconsistent sums");
  75. $last = $sum['diag1'];
  76. for($x = 0; $x < count($input); $x++){
  77.     if($last != $sum['col'][$x]) die("Invalid data: inconsisten sums");
  78.     if($last != $sum['row'][$x]) die("Invalid data: inconsisten sums");
  79. }
  80.  
  81. echo "Magic square";
Advertisement
Add Comment
Please, Sign In to add comment