aboutsummaryrefslogtreecommitdiff
path: root/challenge-089/henry-wong/php/ch-2.php
blob: 41146f3a13d6b49773254c1e98d1b412f9e8ab93 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php

/**
There are two rules for constructing an odd magic square 
1. "top right" 
2. "if the place is occupied, go one down"
**/

function solution($N) {
    if ($N % 2 == 0) {
        // I only know how to solve odd size magic squares for now.
        // I'll have figure out even magic squares later.
       return false;
    }
    $board = [];
    $numbers = $N * $N;
    for ($i = 1 ; $i <= $numbers; $i++) {
        if ($i == 1) {
            // top middle
            $y = 0;
            $x = ((int)($N / 2));  # would have add +1 but we starting with base 0
            $board[$y][$x] = $i;
            
        } else {
            // check if top right is empty
            $y-=1;
            $x+=1;
            $sy = $y < 0 ? $N - 1 : $y;
            $sx = $x >= $N ? 0 : $x;
            if (! isset($board[$sy][$sx])) {
                 // if empty - then assign number
                $board[$sy][$sx] = $i; 
                $y = $sy;
                $x = $sx;
            } else {
                // else go down a row.                
                $x-=1;
                $y+=2;
                $board[$y][$x] = $i;
                
            }           
        }
    }
    // clean up sort the key correctly
    
    for($i = 0; $i < $N; $i++) {
        ksort($board[$i]);
    };
    ksort($board);
    return $board;
}

print_r(solution(3)); // 3x3
print_r(solution(5)); // 5x5