7
$\begingroup$

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.

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

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[1];

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
$\endgroup$
  • $\begingroup$ I tried your suggestion and it still doesn't seem to work $\endgroup$ – Ganyo10 Dec 9 '19 at 18:25
  • $\begingroup$ @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? $\endgroup$ – m_goldberg Dec 9 '19 at 18:43
  • $\begingroup$ @Ganyo10 have you tried copying each statement in a separate cell? Maybe some parsing issue. $\endgroup$ – user13892 Dec 10 '19 at 22:35
1
$\begingroup$
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.

$\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.