Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $input = <<<END
- 5
- 1 9 12 20 23
- 17 25 3 6 14
- 8 11 19 22 5
- 24 2 10 13 16
- 15 18 21 4 7
- END;
- function remove_empty($a){
- if($a){
- return true;
- }
- }
- $input = explode("\n", $input);
- array_shift($input); //remove the first line
- foreach($input as $key => $value){
- $input[$key] = explode(" ", $value);
- }
- foreach($input as $key => $value){
- $input[$key] = array_filter($input[$key], "remove_empty");
- $input[$key] = array_values($input[$key]);
- }
- //var_dump($input);
- $numbers = array();
- foreach($input as $key => $value){
- foreach($value as $number){
- if(in_array($number, $numbers)) die("Invalid data: missing or repeated number");
- $numbers[] = $number;
- }
- }
- sort($numbers);
- //var_dump($numbers);
- $last = 0;
- for($x = 0; $x < count($numbers); $x++){
- if($numbers[$x] == $numbers[$x+1]) die("Invalid data: missing or repeated number");
- }
- //now actually test if each collum and row adds up
- $sum = array();
- $sum['diag1'] = 0;
- $sum['diag2'] = 0;
- for($x = 0; $x < count($input[0]); $x++){
- $sum['col'][$x] = 0;
- for($y = 0; $y < count($input); $y++){
- //$input[$y][$y] and we are moving down the collum
- $sum['col'][$x] += $input[$x][$y]; //add up in each collum, php should be alright with $sum[n] not having a preset value
- }
- }
- for($y = 0; $y < count($input); $y++){
- $sum['row'][$y] = 0;
- for($x = 0; $x < count($input[0]); $x++){
- $sum['row'][$y] += $input[$x][$y];
- }
- }
- for($z = 0; $z < count($input); $z++){
- $sum['diag1'] += $input[$z][$z];
- $sum['diag2'] += $input[$z][count($input)-$z-1];
- }
- //var_dump($sum);
- if($sum['diag1'] != $sum['diag2']) die("Invalid data: inconsistent sums");
- $last = $sum['diag1'];
- for($x = 0; $x < count($input); $x++){
- if($last != $sum['col'][$x]) die("Invalid data: inconsisten sums");
- if($last != $sum['row'][$x]) die("Invalid data: inconsisten sums");
- }
- echo "Magic square";
Advertisement
Add Comment
Please, Sign In to add comment