dde272c4b8
i18n - Build Validation / Validate i18n Builds (24) (push) Has been cancelled
CI - Node.js / Lint (24) (push) Has been cancelled
CI - Node.js / Build (24) (push) Has been cancelled
CI - Node.js / Test (24) (push) Has been cancelled
CI - Node.js / Test - Upcoming Changes (24) (push) Has been cancelled
CI - Node.js / Test - i18n (italian, 24) (push) Has been cancelled
CI - Node.js / Test - i18n (portuguese, 24) (push) Has been cancelled
CD - Docker - GHCR Images / Build and Push Images (push) Has been cancelled
2.2 KiB
2.2 KiB
id, title, challengeType, dashedName
| id | title | challengeType | dashedName |
|---|---|---|---|
| 6a22d77ddf034bc4e35b1d5d | Challenge 356: Magic Square Solver | 28 | challenge-356 |
--description--
Given a 3x3 grid with one missing number (represented as 0), return the missing number that completes the magic square, or "impossible" if no valid number exists.
A magic square is a grid where every row, column, and diagonal adds up to the same number.
--hints--
solveMagicSquare([[2, 7, 6], [9, 0, 1], [4, 3, 8]]) should return 5.
assert.equal(solveMagicSquare([[2, 7, 6], [9, 0, 1], [4, 3, 8]]), 5);
solveMagicSquare([[0, 14, 12], [18, 10, 2], [8, 6, 16]]) should return 4.
assert.equal(solveMagicSquare([[0, 14, 12], [18, 10, 2], [8, 6, 16]]), 4);
solveMagicSquare([[12, 17, 16], [19, 0, 10], [14, 13, 18]]) should return "impossible".
assert.equal(solveMagicSquare([[12, 17, 16], [19, 0, 10], [14, 13, 18]]), "impossible");
solveMagicSquare([[15, 35, 31], [43, 27, 11], [23, 19, 0]]) should return 39.
assert.equal(solveMagicSquare([[15, 35, 31], [43, 27, 11], [23, 19, 0]]), 39);
solveMagicSquare([[26, 41, 14], [47, 35, 0], [32, 29, 44]]) should return "impossible".
assert.equal(solveMagicSquare([[26, 41, 14], [47, 35, 0], [32, 29, 44]]), "impossible");
--seed--
--seed-contents--
function solveMagicSquare(grid) {
return grid;
}
--solutions--
function solveMagicSquare(grid) {
const flat = grid.flat();
const zeroIndex = flat.indexOf(0);
const row = Math.floor(zeroIndex / 3);
const col = zeroIndex % 3;
const target = grid.find(r => !r.includes(0))
.reduce((sum, n) => sum + n, 0);
const missing = target - grid[row].reduce((sum, n) => sum + n, 0);
const filled = grid.map((r, ri) =>
r.map((n, ci) => (ri === row && ci === col) ? missing : n)
);
const check = (arr) => arr.reduce((sum, n) => sum + n, 0) === target;
for (let i = 0; i < 3; i++) {
if (!check(filled[i])) return "impossible";
if (!check(filled.map(r => r[i]))) return "impossible";
}
if (!check([filled[0][0], filled[1][1], filled[2][2]])) return "impossible";
if (!check([filled[0][2], filled[1][1], filled[2][0]])) return "impossible";
return missing;
}