4
$\begingroup$

I was trying to produce a little animation with Manipulate, where a Regular Poligon with N sides is displayed behind the previous polygon with N-1 sides , each one with a RandomColor. I wrote this piece of code:

Manipulate[
 Graphics[Reverse[
   Style[RegularPolygon[#], RandomColor[]] & /@ Range[3, l, 1]]] , {l,
   3, 8, 1}]

The problem is that the color keeps changing even for the Polygons on the front. How can I avoid this? Once the color for a polygon is fixed it should not change anymore.

$\endgroup$

3 Answers 3

4
$\begingroup$

A simple approach is to use SeedRandom to block the randomness of RandomColor when Seed keeps the same. But the drawback of this method is that in multiple runs, the color will keep the same.

Manipulate[Graphics[Reverse[
   Style[RegularPolygon[#], SeedRandom[#]; RandomColor[]] & /@ 
    Range[3, l, 1]]], {l, 3, 8, 1}]

So, to aviod this, a yet simple method is to set SeedRandom's content a bit more random:

k = RandomInteger[{1,1000}];

Manipulate[Graphics[Reverse[
   Style[RegularPolygon[#], SeedRandom[k #]; RandomColor[]] & /@ 
    Range[3, l, 1]]], {l, 3, 8, 1}]

Then everything will be fine!

$\endgroup$
1
  • $\begingroup$ oh thanks, i am relatively new to mathematica but i am really enjoying it. update:nvm it was wrong $\endgroup$
    – Alucard
    Aug 12, 2016 at 6:55
7
$\begingroup$

You should only generate the colors once.

With[{colors = RandomColor[8 - 2]},
  Manipulate[
    Graphics[{{colors[[# - 2]], RegularPolygon[#]} & /@ Range[n, 3, -1]}], 
    {n, 3, 8, 1, SetterBar}]]

demo

$\endgroup$
4
$\begingroup$

Here is my revision

color = RandomColor[6];
Manipulate[
           Graphics[{color[[# - 2]], RegularPolygon[#]} & /@ Range[l, 3, -1]], 
           {l, 3, 8, 1}]

enter image description here

$\endgroup$
3
  • $\begingroup$ how would you modify the code if you don't want to preeventively store the entire set of colors before using manipulate? suppose I set the upper limit of manipulate at 5, , the other colors stored are wasted $\endgroup$
    – Alucard
    Aug 12, 2016 at 7:15
  • $\begingroup$ This seems to duplicate my earlier answer. What value does it add over my answer? $\endgroup$
    – m_goldberg
    Aug 12, 2016 at 7:35
  • $\begingroup$ i upvoted both. i asked him a question because i saw his message was just 1 minute old and i thought he would be still online. $\endgroup$
    – Alucard
    Aug 12, 2016 at 7:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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