Skip to content

Instantly share code, notes, and snippets.

@MCPE-PC
Last active July 8, 2019 12:52
Show Gist options
  • Save MCPE-PC/b68419f7478ae7d5b4784c669bda454e to your computer and use it in GitHub Desktop.
Save MCPE-PC/b68419f7478ae7d5b4784c669bda454e to your computer and use it in GitHub Desktop.
// Cubic equation calculator sourced from StackOverflow
const {spawn} = require('child_process');
let nc = spawn('nc', ['ctf.dimigo.hs.kr', 8231]);
nc.stdout.on('data', (data) => {
console.log(data.toString());
if (data.toString().replace(/\n/g, '').startsWith('No. ')) {
const matches = data.toString().match(/([0-9]+)x\^3 ([\+-]) ([0-9]+)x\^2 ([\+-]) ([0-9]+)x ([\+-]) ([0-9]+) = 0/);
let solved = solveCubic(...([matches[1], matches[2] + matches[3], matches[4] + matches[5], matches[6] + matches[7]].map(num => Number(num)))).map(num => Math.round(num));
if (solved.length === 1) {
console.log('Enter manually');
return;
}
if (solved.length === 2) {
solved[2] = solved[0];
}
solved = solved.join(', ');
nc.stdin.write(`${solved}\n`);
}
});
nc.on('close', () => process.exit());
process.stdin.pipe(nc.stdin);
function cuberoot(x) {
var y = Math.pow(Math.abs(x), 1/3);
return x < 0 ? -y : y;
}
function solveCubic(a, b, c, d) {
if (Math.abs(a) < 1e-8) {
a = b; b = c; c = d;
if (Math.abs(a) < 1e-8) {
a = b; b = c;
if (Math.abs(a) < 1e-8)
return [];
return [-b/a];
}
var D = b * b - 4 * a * c;
if (Math.abs(D) < 1e-8)
return [-b/(2*a)];
else if (D > 0)
return [(-b+Math.sqrt(D))/(2*a), (-b-Math.sqrt(D))/(2*a)];
return [];
}
var p = (3*a*c - b*b)/(3*a*a);
var q = (2*b*b*b - 9*a*b*c + 27*a*a*d)/(27*a*a*a);
var roots;
if (Math.abs(p) < 1e-8) {
roots = [cuberoot(-q)];
} else if (Math.abs(q) < 1e-8) {
roots = [0].concat(p < 0 ? [Math.sqrt(-p), -Math.sqrt(-p)] : []);
} else {
var D = q*q/4 + p*p*p/27;
if (Math.abs(D) < 1e-8) {
roots = [-1.5*q/p, 3*q/p];
} else if (D > 0) {
var u = cuberoot(-q/2 - Math.sqrt(D));
roots = [u - p/(3*u)];
} else {
var u = 2*Math.sqrt(-p/3);
var t = Math.acos(3*q/p/u)/3;
var k = 2*Math.PI/3;
roots = [u*Math.cos(t), u*Math.cos(t-k), u*Math.cos(t-2*k)];
}
}
for (var i = 0; i < roots.length; i++)
roots[i] -= b/(3*a);
return roots;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment