Revise the code of randomWalkPoints to have the entity go with equal probability
ID: 3874077 • 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.
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
***********************PLEASE FIND INLINE COMMENTS FOR CODE EXPLANATION**********************************
function [lst] = randomWalkPoints(n)
% RANDOMWALKPOINTS Function to produce a random walk, where at each time
% step the entity goes in N, E, W or S 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.
% Here x represents the x coordinate of a point and y represents the y
% coorinate. Since, we assume that the random walk is always started from origin,
% lets assign x = 0 and y = 0
x = 0;
y = 0;
% Since n steps from origin results in n + 1 points, lets create a vector
% 'lst' with 'n + 1' rows and 2 columns.
% This vector is used for storing x and y values of n + 1 points.
lst = zeros(n + 1,2);
% firstt point is always origin, hence, initialize first row to (0, 0).
lst(1, :) = [0 0];
% run a loop for n steps. Here i+1 represents the row number.
for i = 1:n
% now, lets pick a random integer between 1, 2, 3 or 4
% where 1 means go North, 2 means go South, 3 means go East,
% 4 means go West.
randNumber = randi(4);
% If randNumber is 1, we need to go North, hence, increment y by 1
if randNumber == 1
y = y + 1;
% If randNumber is 2, we need to go South, hence, decrement y by 1
elseif randNumber == 2
y = y - 1;
% If randNumber is 3, we need to go Ease, hence, increment x by 1
elseif randNumber == 3
x = x + 1;
% Else randNumber is 4, we need to go West, hence, decrement x by 1
else
x = x - 1;
% Now copy the values of x and y to the (i+1)th row in lst
lst(i + 1, :) = [x y];
end;
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.