Created
September 28, 2019 23:43
This file contains 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
#!/usr/bin/env node | |
/** | |
* Solve the problem by guessing. | |
* | |
* @param {Int8Array} src | |
* @param {Int8Array} dst | |
* @param {() => void} fn | |
*/ | |
function solve(src, dst, fn) { | |
if (src.length == 0) { | |
fn(); | |
return; | |
} | |
let tmp = new Int8Array(src.length - 1); | |
src.forEach((x) => { | |
dst[0] = x; | |
let k = 0; | |
src.forEach((y, j) => { | |
if (x != y) { | |
tmp[k] = y; | |
k++; | |
} | |
}); | |
solve(tmp, dst.subarray(1), fn); | |
}); | |
} | |
/** | |
* Create a string to show the solution. | |
* | |
* @param {Int8Array} sol | |
*/ | |
function format(sol) { | |
let ad = sol[1]*10 + sol[2], | |
bd = sol[4]*10 + sol[5], | |
cd = sol[7]*10 + sol[8]; | |
return `${sol[0]}/${ad} + ${sol[3]}/${bd} + ${sol[6]}/${cd} = 1`; | |
} | |
/** | |
* Does this guess solve the problem? | |
* | |
* @param {Int8Array} sol | |
* @returns {boolean} | |
*/ | |
function isSolution(sol) { | |
let ad = sol[1]*10 + sol[2], | |
bd = sol[4]*10 + sol[5], | |
cd = sol[7]*10 + sol[8], | |
s = sol[0]/ad + sol[3]/bd + sol[6]/cd; | |
return s > 0.9999 && s < 1.0001; | |
} | |
let n = 9, | |
src = new Int8Array(n).map((x, i) => { | |
return i + 1; | |
}), | |
dst = new Int8Array(n); | |
solve(src, dst, () => { | |
if (isSolution(dst)) { | |
console.log(format(dst)); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment