aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--challenge-089/henry-wong/php/ch-1.php24
-rw-r--r--challenge-089/henry-wong/php/ch-2.php54
2 files changed, 78 insertions, 0 deletions
diff --git a/challenge-089/henry-wong/php/ch-1.php b/challenge-089/henry-wong/php/ch-1.php
new file mode 100644
index 0000000000..4303a961b3
--- /dev/null
+++ b/challenge-089/henry-wong/php/ch-1.php
@@ -0,0 +1,24 @@
+<?php
+
+function gcd($a, $b) {
+ // could of used https://www.php.net/manual/en/function.gmp-gcd.php
+ return ($a % $b) ? gcd($b,$a % $b) : $b;
+}
+function solutions($N) {
+ // $N can't be less than 2
+ if ($N <= 1) {
+ return false;
+ }
+ $total = 0;
+ for ($i = 1; $i <= $N; $i++) {
+ for ($next = $i + 1; $next <= $N; $next++) {
+ // debug purpose
+ printf ("gcd(%s, %s)\n", $i, $next);
+ $total += gcd($i, $next);
+ }
+ }
+ return $total;
+}
+
+echo solutions(3), "\n";
+echo solutions(4), "\n"; \ No newline at end of file
diff --git a/challenge-089/henry-wong/php/ch-2.php b/challenge-089/henry-wong/php/ch-2.php
new file mode 100644
index 0000000000..41146f3a13
--- /dev/null
+++ b/challenge-089/henry-wong/php/ch-2.php
@@ -0,0 +1,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 \ No newline at end of file