Revise the code of randomWalkPoints to have the entity go with equal probability
ID: 3874628 • Letter: R
Question
Revise the code of randomWalkPoints to have the entity go with equal probability in a N, S, E, or W direction. Hint: Choose the direction based on the value of a random integer, 0, 1, 2, or 3. Please note the bolded.
function [lst] = randomWalkPoints(n)
% RANDOMWALKPOINTS Function to produce a random walk, where at each time
% step the entity goes diagonally in a NE, NW, SE, or SW direction, and to
% return a list of the points in the walk
% Pre: n is the number of steps in the walk.
% Post: A list of the points in the walk has been returned.
x = 0;
y = 0;
lst = zeros(n + 1,2);
lst(1, :) = [0 0];
for i = 1:n
if randi([0,1]) == 0
x = x + 1;
else
x = x - 1;
end;
if randi([0,1]) == 0
y = y + 1;
else
y = y - 1;
end;
lst(i + 1, :) = [x y];
end;
Explanation / Answer
Given below is the code for the question.
Please do rate the answer if it was helpful. Thank you
function [lst] = randomWalkPoints(n)
% RANDOMWALKPOINTS Function to produce a random walk, where at each time
% step the entity goes diagonally in a NE, NW, SE, or SW direction, and to
% return a list of the points in the walk
% Pre: n is the number of steps in the walk.
% Post: A list of the points in the walk has been returned.
x = 0;
y = 0;
lst = zeros(n + 1,2);
lst(1, :) = [0 0];
for i = 1:n
r = randi([0,3]); %generate a random number from 0-3
if r == 0 %north
y = y - 1;
elseif r == 1 %south
y = y + 1;
elseif r == 2 %east
x = x + 1;
else %west
x = x - 1;
end
lst(i + 1, :) = [x y];
end;
=================================
output
=================================
randomWalkPoints(10)
ans =
0 0
0 -1
0 -2
-1 -2
0 -2
0 -1
0 0
1 0
0 0
0 1
-1 1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.