How to assign an index on the edge of an array a certain value

I am working on a function the creates a "maze" or NxN array of strings "0". The goal is to move a player "P" in the array randomly through the maze until the player reaches the exit "E" How do i randomly assign an index on the edge of the array the value "E" to represent the exit of the maze?
ex. I need it to look like this
"0" "0" "0" "0"
"0" "0" "0" "0"
"P" "0" "0" "0"
"0" "0" "0" "E"
where "E" is randomly assigned but needs to be on the edge of the array

 Akzeptierte Antwort

Matt J
Matt J am 1 Nov. 2018
Bearbeitet: Matt J am 1 Nov. 2018
Z=false(N);
Z(:,[1,N])=true; Z([1,N],:)=1;
I=find(Z);
n=numel(I);
idx=I(randperm(n,2));
Maze(1:N,1:N)="0" ;
Maze(idx(1))="P";
Maze(idx(2))="E"

10 Kommentare

This code places "E" in the same spot every time. I need it to be randomly assigned with the only restriction being it has to be on the edge of the array
And it cannot be in the same spot as "P"
Hum, I think Z should be
Z([1, end], :) = true;
Z(:, [1, end]) = true;
Otherwise you're just getting the corners
Another way to create that matrix I is to use the demo function spiral, bypassing Z entirely:
I = find(N^2 - spiral(N) < 4*(N-1));
Another way to create that matrix I is to use the demo function spiral, bypassing Z entirely:
There's a loop under the hood with that, though. But if we don't care, here's yet another way.
I = find( (pascal(N)<2) + (rot90(pascal(N)<2,-2)) )
that takes care of putting "E" on the edge of the array, but "E" sometimes over writes the spot of "P". How do i prevent this?
for instance if i use a 2x2 array for the size, "P" is generated first, then when "E" is generated, if the indexes are the same, "E" takes the spot of "P" and i end up with something like this
"0" "E"
"0" "0"
Matt J
Matt J am 1 Nov. 2018
Bearbeitet: Matt J am 1 Nov. 2018
Are you generating "P" on your own? My code generates both "P" and "E" for you, and in a non-overlapping manner.
If you already have a Maze with a pre-placed "P", then modify as follows:
Z=false(N);
Z(:,[1,N])=true; Z([1,N],:)=1;
Z(Maze=="P")=0;
I=find(Z);
idx=I(randperm(numel(I),1));
Maze(idx)="E"
That worked, Thanks

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by