Problem of Apollonius: Difference between revisions

m (→‎{{header|MUMPS}}: Use trans tag)
Line 97:
free(r1); free(r2);
}</lang>
=={{header|D}}==
Translated and improved from the Java version.
<lang d>import std.stdio: writeln;
import std.typecons: Tuple;
import std.math: sqrt;
 
 
alias Tuple!(double, "x", double, "y", double, "r") Circle;
 
enum Tangent { externally, internally }
 
 
/**
Solves the Problem of Apollonius (finding a circle tangent to three
other circles in the plane).
 
Params:
c1 = First circle of the problem
c2 = Second circle of the problem
c3 = Third circle of the problem
t1 = if the solution should be externally or internally tangent to c1
t2 = if the solution should be externally or internally tangent to c2
t3 = if the solution should be externally or internally tangent to c3
 
Returns: The Circle that is tangent to c1, c2 and c3.
*/
Circle solveApollonius(const Circle c1, const Circle c2, const Circle c3,
Tangent t1, Tangent t2, Tangent t3) {
double s1 = (t1 == Tangent.externally) ? 1.0 : -1.0;
double s2 = (t2 == Tangent.externally) ? 1.0 : -1.0;
double s3 = (t3 == Tangent.externally) ? 1.0 : -1.0;
 
double v11 = 2 * c2.x - 2 * c1.x;
double v12 = 2 * c2.y - 2 * c1.y;
double v13 = c1.x ^^ 2 - c2.x ^^ 2 +
c1.y ^^ 2 - c2.y ^^ 2 -
c1.r ^^ 2 + c2.r ^^ 2;
double v14 = 2 * s2 * c2.r - 2 * s1 * c1.r;
 
double v21 = 2 * c3.x - 2 * c2.x;
double v22 = 2 * c3.y - 2 * c2.y;
double v23 = c2.x ^^ 2 - c3.x ^^ 2 +
c2.y ^^ 2 - c3.y ^^ 2 -
c2.r ^^ 2 + c3.r ^^ 2;
double v24 = 2 * s3 * c3.r - 2 * s2 * c2.r;
 
double w12 = v12 / v11;
double w13 = v13 / v11;
double w14 = v14 / v11;
 
double w22 = v22 / v21 - w12;
double w23 = v23 / v21 - w13;
double w24 = v24 / v21 - w14;
 
double P = -w23 / w22;
double Q = w24 / w22;
double M = -w12 * P - w13;
double N = w14 - w12 * Q;
 
double a = N * N + Q ^^ 2 - 1;
double b = 2 * M * N - 2 * N * c1.x +
2 * P * Q - 2 * Q * c1.y +
2 * s1 * c1.r;
double c = c1.x ^^ 2 + M ^^ 2 - 2 * M * c1.x +
P * P + c1.y ^^ 2 - 2 * P * c1.y - c1.r ^^ 2;
 
// find a root of a quadratic equation.
// This requires the circle centers not to be e.g. colinear
double D = b*b - 4*a*c;
double rs = (-b - sqrt(D)) / (2 * a);
 
double xs = M + N * rs;
double ys = P + Q * rs;
 
return Circle(xs, ys, rs);
}
 
 
void main() {
auto c1 = Circle(0.0, 0.0, 1.0);
auto c2 = Circle(4.0, 0.0, 1.0);
auto c3 = Circle(2.0, 4.0, 2.0);
 
alias Tangent.externally e;
writeln(solveApollonius(c1, c2, c3, e, e, e));
 
alias Tangent.internally i;
writeln(solveApollonius(c1, c2, c3, i, i, i));
}
</lang>
Output:
<pre>Tuple!(double,"x",double,"y",double,"r")(2, 2.1, 3.9)
Tuple!(double,"x",double,"y",double,"r")(2, 0.833333, 1.16667)
</pre>
 
=={{header|Java}}==
Anonymous user