# Function under Button, need help [closed]

I would like to put this function under button so I can just press button to evaluate instead of having to shift+enter

f[] := Block[{u, t, r},
u = Random[] + Random[];
t = Random[] 2 Pi;
r = 1;
{r Cos[t], r Sin[t]}]

a = Sort[Table[f[], {5}]]
b = a[[Last[FindShortestTour[a]]]]

• try this f[] := Block[{u, t, r}, u = Random[] + Random[]; t = Random[] 2 Pi; r = 1; {r Cos[t], r Sin[t]}] a = Sort[Table[f[], {5}]] b = a[[Last[FindShortestTour[a]]]] – tsin Dec 19 '15 at 18:04
• This works g[] := Block[{u, t, r}, u = Random[] + Random[]; t = Random[] 2 Pi; r = 1; {r Cos[t], r Sin[t]}] ; a = Sort[Table[g[], {5}]] ; b = a[[Last[FindShortestTour[a]]]] – Hubble07 Dec 19 '15 at 18:19
• when I pase it here it get broken because of bad enter placements – tsin Dec 19 '15 at 18:39
• Possible duplicate: Button generate output – garej Dec 19 '15 at 19:22

I think this is what you are trying to achieve. Just check if the output is correct. One problem is that as you keep on clicking the button the results gets accumulated below the previous one. Note that I changed the argument of Cos function to u (you have defined it but not used it).

h := Block[{u, t, r = 1, a, b},
a = Sort[Table[
u = Random[] + Random[]; t = Random[] 2 Pi;
{r Cos[u], r Sin[t]}, {5}]];
b = a[[Last[FindShortestTour[a]]]]
];

Button["Click to Create", Print@h]


### Update

[m_goldbeg]: perhaps this small modification will serve the OP needs a little better.

h :=
Block[{u, t, r = 1, a},
a =
Sort @
Table[
u = Random[] + Random[];
t = Random[] 2 Pi;
{r Cos[u], r Sin[t]},
{5}];
b = a[[Last[FindShortestTour[a]]]];]

Button["Click to Create", h, Method -> "Queued"]


Dynamic @ b

{{-0.173037, 0.902559}, {0.300649, 0.188876}, {0.894028, 0.581573},
{0.856143, 0.922075}, {0.64084, 0.997153}, {-0.173037, 0.902559}}

• Thx for that answer. Can you help me with other function? It used to work but now it doesnt and I dont know why. g[n_] := {g[n - 1], Blue, Disk[b[[n - 1]]/2 + b[[n]]/2,EuclideanDistance[b[[n - 1]], b[[n]]]/2]} It used to draw moons when I put it in my graphics. b is table from the previous function – tsin Dec 19 '15 at 18:56
• I fail to understand why you are using recursion for g. I think you should ask this as a separate question providing some explanation for defining such a functional form. – Hubble07 Dec 19 '15 at 19:11
• I want to draw given amount of circles, so for example n=5 it should draw 5 circles etc. – tsin Dec 19 '15 at 19:25
• @tsin, in this answer b is included in the Block symbol list, so when the Block exits b reverts to its global value (which may not be defined). If you need to use b in subsequent code simply remove it from the Block symbol list. – Simon Woods Dec 19 '15 at 20:16