4
$\begingroup$

I'm trying to develop my Wolfram programming skills and set myself an exercise of creating concentric circles using a recursive delayed function:

drawCircle[x_, y_, r_] :=
     Graphics[Circle[{x, y}, r]];
     If[r > 10, drawCircle[x, y, r/2], Break];

Since I'm not using a Do, While or For loop, my use of Break is probably wrong too, but my logic is to exit recursion when r is less than 10.

This code creates a series of overlay objects rather than concentric circles:

enter image description here

I have tried joining the output objects but without much success.

Desired output (using delayed function recursion):

enter image description here

$\endgroup$
7
$\begingroup$

In fact, since Mathematica does not care about nesting lists for graphics primitives, the most simple solution is this:

drawCircle[x_, y_, r_ /; r > 10] := {Circle[{x, y}, r], drawCircle[x, y, r/2]};
drawCircle[__] := {}
drawCircle[0, 0, 200] // Graphics

Mathematica graphics

Now you will say, wait, that is not what I wanted and you are correct. Dividing radii is not the correct operation. You need to subtract in the recursion:

drawCircle[x, y, r - 50]

and then you get

drawCircle[0, 0, 250] // Graphics

Mathematica graphics

$\endgroup$
  • $\begingroup$ I had not thought about using the condition as a function argument - nice. Thank you! $\endgroup$ – awyr_agored Jan 19 '18 at 3:06
3
$\begingroup$
Clear[drawCircle];
drawCircle[a_: 0, b_: 1/2][{x_, y_}, r_] := Circle[{x, y}, r] /. 
  c_Circle :> If[r > 10, {c, drawCircle[a, b][{x, y}, a + b r]}, c]

Graphics[drawCircle[][{0, 0}, 200]]

enter image description here

Graphics[drawCircle[-50, 1][{0, 0}, 250]]

enter image description here

$\endgroup$
1
$\begingroup$
Clear[drawCircle];
drawCircle[{x_, y_}, r_] := 
 If[r > 10, drawCircle[{x, y}, r/2], Circle[{x, y}, r]]

Cases[Trace[drawCircle[{0, 0}, 200]], _Circle, -1] // Union // Graphics
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.