How to simulate a random castle in a chessboard?

조회 수: 1 (최근 30일)
Osama Tabbakh
Osama Tabbakh 2020년 2월 16일
댓글: Osama Tabbakh 2020년 2월 18일
%the randomly generated castle should be within the chessboard, let say zeros matrix:
CB = zeros (8,8); % chessboard
% and the castle must be the one in this matrix:
C = 1; % Castle
% now randomly generate a castle:
CB (round((8-1)*rand+1),round((8-1)*rand+1))= C; % random generatation for castle
% then i will find out where is the generated castle and i want to generate also randomly a lot of castles, which are not in the same row and column:
[row,column] = find (CB);
x = round((8-1)*rand+1);
y = round((8-1)*rand+1);
I = length (row);
while row(I,:)~= x && row(I,:)~= y && column(I,:)~= y && column(I,:)~= x
CB (x,y)= C;
[row,column] = find (CB);
I = length (row);
x = round((8-1)*rand+1);
y = round((8-1)*rand+1);
end
disp (CB)
the problem is, i dont want to accept any number from row and column in the while loop. I tried with any, all and ismember (functions) but i is not working.
  댓글 수: 2
Giuseppe Inghilterra
Giuseppe Inghilterra 2020년 2월 16일
I don' understand well which is your problem.
Firstly, I advise you to use "randi" function, instead of round((8-1)*rand+1) (reference: https://www.mathworks.com/help/matlab/ref/randi.html) . In this way you generate random integer numbers.
Secondly, you could generate two random integer vectors:
x = randi(8,10,1); %this generates a vector of size [10,1] where each entry is within range [1,8].
y = randi(8,10,1);
CB(x,y) = C;
In this way CB matrix has value C=1 in 10 positions defined by pairs (x,y).
But, I don't understand what you want to do, i.e do you want to generate one random pair (x_i,y_i) per time and then if CB(x_i,y_i) is zero then you fill with 1 otherwise you stop while loop?
Osama Tabbakh
Osama Tabbakh 2020년 2월 16일
yes, i want to fill the matrix (zeros) with 1 (one by one), but if one is in a position, the next one should not be in the same column and row.

댓글을 달려면 로그인하십시오.

채택된 답변

Giuseppe Inghilterra
Giuseppe Inghilterra 2020년 2월 17일
Hi,
if you try to run this code:
close all
clear all
clc
n = 8; %chessboard size
CB = zeros(n,n); %init chessboard
k = 0;
niter = 0;
while(k<n) %stop condition
x = randi(n);
y = randi(n);
if sum(CB(x,:))+sum(CB(:,y)) == 0
CB(x,y) = 1;
k = k+1;
end
niter = niter + 1;
end
spy(CB,'ro',28)
hold on
spy(~CB,'b+',28)
you fill with 1 if there are no ones in the same row or column, obtaining following result (this plot changes every time due to introduced randomness with randi function):
Hope this helps.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 LMI Solvers에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by