# Randomly generated coordinates

I want to code that will do the following:

Write a Mathematica function called randomHop that takes as its argument a list containing two coordinates x and y; your definition should begin

randomHop[{x_, y_}] :=


The function should then generate a random integer r equal to 1 or 2 (this should be locally scoped), and then

• if r is equal to 1, return {{0.5, 0.5}, {0.5, 0.5}} . {x, y};
• if r is 2, return {{-0.5, -0.5}, {0.5, -0.5}} . {x, y} + {1.0, 0}.

I have so far tried

randomHop[{x_, y_}] := (
r = RandomInteger[{1, 2}]
If[r == 1, Return[{{0.5, 0.5}, {0.5, 0.5}}.{x, y}],
Return[{{-0.5, -0.5}, {0.5, -0.5}} . {x, y} + {1.0, 0}]])


but it's not working, and I don't know why. Any help would be appreciated.

• does it work if you add a ; right after r = RandomInteger[{1, 2}] ? – Nasser Dec 9 '19 at 3:57
• No it doesn't @Nasser – Ganyo10 Dec 9 '19 at 18:24

To localize r, I would use Module. Otherwise, the only changes needed are inserting a missing semicolon and getting rid of the unnecessary Return calls.

ClearAll[randomHop];
randomHop[{x_,y_}]:=Module[{
r
},
r=RandomInteger[{1,2}];
If[r==1,
{{0.5,0.5},{0.5,0.5}}.{x,y},
{{-0.5,-0.5},{0.5,-0.5}}.{x,y}+{1,0}
]
];

SeedRandom;

NestList[randomHop,{1,2},10];

{{1, 2}, {-0.5, -0.5}, {1.5, 0.}, {0.75, 0.75}, {0.25, 0.}, {0.125, 0.125},
{0.125, 0.125}, {0.125, 0.125}, {0.875, 0.}, {0.4375, 0.4375}, {0.5625, 0.}}


Visualize the path like:

NestList[randomHop,{1,2},10]//ListLinePlot

• I tried your suggestion and it still doesn't seem to work – Ganyo10 Dec 9 '19 at 18:25
• @Ganyo10. Your comment is opaque. My answer shows it worked fine form me. What went wrong when you ran my code in on your system? – m_goldberg Dec 9 '19 at 18:43
• @Ganyo10 have you tried copying each statement in a separate cell? Maybe some parsing issue. – user13892 Dec 10 '19 at 22:35
randomHop[{x_, y_}] := If[RandomInteger[{1, 2}] == 1, {{0.5, 0.5}, {0.5, 0.5}}.{x, y},
{{-0.5, -0.5}, {0.5, -0.5}}.{x, y} + {1.0, 0}]


also works.