Skip to content

Instantly share code, notes, and snippets.

@NimaGhaedsharafi
Created May 12, 2021 10:59
Show Gist options
  • Save NimaGhaedsharafi/afbe185d57abe68f9a6766210f10e0c2 to your computer and use it in GitHub Desktop.
Save NimaGhaedsharafi/afbe185d57abe68f9a6766210f10e0c2 to your computer and use it in GitHub Desktop.
function formingMagicSquare($s) {
if (checkMagic($s)) {
return 0;
}
$cost = 0;
if ($s[1][1] != 5) {
$cost = abs(5 - $s[1][1]);
$s[1][1] = 5;
}
if (checkMagic($s)) {
return $cost;
}
// check all pairs
/**
(0,0), (2,2) = 10
(0,1), (2,1) = 10
(2,0), (0,2) = 10
(1,0), (1,2) = 10
**/
$pairs = [
[[0,0], [2,2]],
[[0,1], [2,1]],
[[2,0], [0,2]],
[[1,0], [1,2]]
];
$mincost = 0;
$tmp = $s;
foreach ($p in $pairs)
{
$t = ($s[$p[0][0],p[0][1]] + $s[$p[1][0],p[1][1]] - 10);
if ($t == 0) {
continue;
}
// check this leg
$tmp[$p[0][0],p[0][1]] += $t;
}
return $mincost + $cost;
}
function checkMagic($s)
{
// vertically
$sum = 0;
for ($i = 0; $i < 3; $i++) {
for ($j = 0; $j < 3; $j++) {
$sum += $s[$i][$j];
}
if ($sum != 15) {
return false;
}
$sum = 0;
}
// horizontally
$sum = 0;
for ($j = 0; $j < 3; $j++) {
for ($i = 0; $i < 3; $i++) {
$sum += $s[$i][$j];
}
if ($sum != 15) {
return false;
}
$sum = 0;
}
// diagonally
$sum = 0;
for ($j = 0; $j < 3; $j++) {
$sum += $s[$j][$j];
}
if ($sum != 15) {
return false;
}
$sum = 0;
for ($j = 0; $j < 3; $j++) {
$sum += $s[2 - $j][$j];
}
if ($sum != 15) {
return false;
}
return true;
}
$s = [[8, 3, 4], [1, 4, 9], [6, 7, 1]];
echo formingMagicSquare($s);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment