Clear Filters
Clear Filters

How do i change these for loops so that I get the right numbers for this "game"?

1 view (last 30 days)
So basically I have an R-by-C game board, with certain amount of money placed on each board square. I am asked to start from the top-left corner of the board (r=c=1) and move all the way to the bottom-right corner (r=R, c=C), moving right, down, or diagonal at each step. The diagonal moves are free, but moves right or down, have a $5 penalty and additionally I cannot collect the money from the cell visited. It says you can only collect the money from each board square that you pass through.
My program is now set up to add the money from the square I am on to the previous amount. I guess I am confused by the wording if you pass through the square does that mean you have to look to the previous square? Here's my function.
function [C,P]= dynamicprogramming(S)
C(1,1)=S(1,1);
%rows
rows=numel(S(:,1));
%columns
columns=numel(S(1,:));
for i=1:rows(end)
for j=1:columns(end)
Options=[-inf -inf -inf];
if j~=1
Options(1)=C(i,j-1)+S(i,j)-5;
end
if i~=1
Options(2)=C(i-1,j)+S(i,j)-5;
end
if i~=1 && j~=1
Options(3)=C(i-1,j-1)+S(i,j);
end
[max_ij,path_ij]=max(Options);
if i~=1 || j~=1
C(i,j)=max_ij;
P(i,j)=path_ij;
end
end
end
  2 Comments
Jan
Jan on 1 Feb 2017
Edited: Jan on 1 Feb 2017
Please do not bump questions without providing new details.
I do not understand what you are asking for. Just a comment to your code:
[rows, columns] = size(S); % Instead of: numel(S(:,1));
% columns = numel(S(1,:)) would be: columns = size(S, 2);
for i=1:rows % Without (end)
for j=1:columns % Without (end)

Sign in to comment.

Accepted Answer

Geoff Hayes
Geoff Hayes on 1 Feb 2017
Edited: Geoff Hayes on 1 Feb 2017
Mohannad - the you can only collect the money from each board square that you pass through means that you can only collect money for those squares that you "land" on. So if you are on the starting square (1,1) and move to a subsequent square (down, right, or diagonal) then that square that you move to is considered to be a square that you passed through. This would be true for all other moves too.

More Answers (0)

Categories

Find more on Strategy & Logic in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!