필터 지우기
필터 지우기

Monte Carlo Simulation (chutes and ladders)

조회 수: 3 (최근 30일)
E
E 2013년 10월 25일
답변: arushi 2024년 8월 29일
I'm trying to work a monte carlo simulation for a chutes and ladders game. The board is nine squares. You can only roll a 1 or a 2. If you land on square 3, you are laddered to square 6. if you land on square 8, you chute down to square 2. If you land on square 9, you win the game. I'm trying to determine the average number of rolls it takes to win the game. We are required to run this simulation several times to see if the average changes based on how many times you run the simulation. This is what I have so far. Any help is appreciated.
n=5;
for t=1:n
pos=0;
move=0;
while pos(t)<9
roll(t)=round(a+(b-a).*rand(1));
pos(t)=pos(t)+roll(t);
if pos(t)=3
then pos(t)=6
end
if pos(t)=8
then pos(t)=2
end
move(t)=move(t)+1;
end
end

답변 (1개)

arushi
arushi 2024년 8월 29일
Hi E,
Below is a corrected version of your code:
% Parameters
num_simulations = 5; % Number of simulations to run
results = zeros(1, num_simulations); % Array to store results of each simulation
% Simulation loop
for t = 1:num_simulations
pos = 0; % Starting position
move = 0; % Move counter
% Play until the player wins
while pos < 9
% Roll a 1 or 2
roll = randi([1, 2]); % Random integer between 1 and 2
pos = pos + roll; % Update position
% Check for ladder and chute
if pos == 3
pos = 6; % Ladder from 3 to 6
elseif pos == 8
pos = 2; % Chute from 8 to 2
end
% Increment move counter
move = move + 1;
end
% Store the number of moves for this simulation
results(t) = move;
end
% Calculate the average number of rolls
average_moves = mean(results);
% Display the results
fprintf('Average number of rolls to win: %.2f\n', average_moves);
Hope this helps.

카테고리

Help CenterFile Exchange에서 Just for fun에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by