Last active
August 29, 2020 10:27
-
-
Save akainth015/fcf06f1539d292dfc5b9127af772d65f to your computer and use it in GitHub Desktop.
Solving Greco-Latin squares for Magic Squares
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Replace these variables with your own | |
const chemEcoSquare = `A5 B4 C3 D2 E1 | |
E4 A3 B2 C1 D5 | |
D3 E2 A1 B5 C4 | |
C2 D1 E5 A4 B3 | |
B1 C5 D4 E3 A2 `; | |
let map = { | |
A: 0, | |
B: 1, | |
C: 2, | |
D: 3, | |
E: 4, | |
1: 0, | |
2: 1, | |
3: 2, | |
4: 3, | |
5: 4 | |
}; | |
/** | |
* You can use this site to generate a Greco-latin square | |
* @see https://www.chemical-ecology.net/java/r93-fig6.htm | |
*/ | |
function mkSquareFromChemEco(chemEcoSquare) { | |
return chemEcoSquare.split(" ") | |
.map(it => it.trim()) | |
.filter(it => it !== ""); | |
} | |
const square = mkSquareFromChemEco(chemEcoSquare); | |
function getBase10(square) { | |
return square | |
.map(it => it.split("").map(character => map[character]).join("")) | |
.map(it => parseInt(it, Math.sqrt(square.length)) + 1); | |
} | |
function verify() { | |
const out = getBase10(square); | |
const width = Math.sqrt(out.length); | |
// Make the base10 a 2d array | |
const out2d = new Array(width).fill(0).map((_, i) => { | |
return out.slice(i * width, (i + 1) * width); | |
}); | |
const diagonal = []; | |
for (let i = 0; i < 5; i++) { | |
diagonal.push(out2d[i][i]); | |
} | |
const sum = (a, b) => a + b; | |
const r1o = out2d[0].reduce(sum); | |
const rws = out2d.every(it => it.reduce(sum) === r1o); | |
const dgo = diagonal.reduce(sum); | |
const dgs = dgo === r1o; | |
console.debug(r1o, rws, dgo, dgs); | |
return ( | |
rws && dgs | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment