
Task

Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right).

There is an   algebraic solution   which is pretty straightforward.



The solutions to the example in the code are shown in the diagram   (below and to the right).

The red circle is "internally tangent" to all three black circles,   and the green circle is "externally tangent" to all three black circles.




define :circle [x y r][]
 
solveApollonius: function [c1 c2 c3 s1 s2 s3][
    v11: sub 2*c2\x 2*c1\x
    v12: sub 2*c2\y 2*c1\y
    v13: (sub (sub c1\x*c1\x c2\x*c2\x) + (sub c1\y*c1\y c2\y*c2\y) c1\r*c1\r) + c2\r*c2\r
    v14: sub 2*s2*c2\r 2*s1*c1\r
 
    v21: sub 2*c3\x 2*c2\x
    v22: sub 2*c3\y 2*c2\y
    v23: (sub (sub c2\x*c2\x c3\x*c3\x) + (sub c2\y*c2\y c3\y*c3\y) c2\r*c2\r) + c3\r*c3\r
    v24: sub 2*s3*c3\r 2*s2*c2\r
 
    w12: v12/v11
    w13: v13/v11
    w14: v14/v11
 
    w22: sub v22/v21 w12
    w23: sub v23/v21 w13
    w24: sub v24/v21 w14
 
    p: neg w23/w22
    q: w24/w22
    m: sub (neg w12)*p w13
    n: sub w14 w12*q
 
    a: dec add n*n q*q
    b: add (sub 2*m*n 2*n*c1\x) + (sub 2*p*q 2*q*c1\y) 2*s1*c1\r
    c: sub sub (sub (c1\x*c1\x) + m*m 2*m*c1\x) + (p*p) + c1\y*c1\y  2*p*c1\y c1\r*c1\r
 
    d: (b*b)-4*a*c
    rs: ((neg b)-sqrt d )/(2*a)
 
    xs: m+n*rs
    ys: p+q*rs
 
    return @[xs ys rs]
]
 
c1: to :circle [0.0 0.0 1.0]
c2: to :circle [4.0 0.0 1.0]
c3: to :circle [2.0 4.0 2.0]
 
print solveApollonius c1 c2 c3 1.0 1.0 1.0
print solveApollonius c1 c2 c3 neg 1.0 neg 1.0 neg 1.0