While loop not working the way I thought

1 回表示 (過去 30 日間)
Zach Harrison
Zach Harrison 2020 年 11 月 30 日
コメント済み: Zach Harrison 2020 年 11 月 30 日
%% Made by Zach Harrison, Final Project Part
clear all
clc
%% Code
i = 1; % Initial parking spot number
n = 30; % Number of parking spots
spot = zeros(2,n); % 0 means spot is open, 1 means spot is full
car = 1; % Car number
while i <= n % Check each parking spot
for k = 1:n
spot(k) = spot;
end
if spot == 1
continue
elseif spot == 0 % Check if spot is open
spot = 1; % Make spot full
text = ['car ', num2str(car),' entered into spot ', num2str(i)];
disp(text)
else
disp('The parking lot is full')
end
k = k + 1;
i = i + 1;
end
car = car + 1;
I want the code to tell a car to park in the closest open parking spot. Code to English, If car comes in, check the first spot, if open go in, if full move on to the next spot and repeat. I could use a lot of ifelse statements but that is long a dirty, but I can't figure out how to make this work.

回答 (2 件)

Sibi
Sibi 2020 年 11 月 30 日
編集済み: Sibi 2020 年 11 月 30 日
i = 1; % Initial parking spot number
n = 30; % Number of parking spots
spot = zeros(1,n); % 0 means spot is open, 1 means spot is full
car = 1; % Car number
if sum(spot) < n
for k = 1:n
if spot(1,k) == 1 % Check each parking spot
continue
else
spot(1,k) = 1; % Make spot full
text = ['car ', num2str(car),' entered into spot ', num2str(k)];
disp(text)
break
end
end
else
disp('The parking lot is full')
end
car=car+1;
try this.
  2 件のコメント
Zach Harrison
Zach Harrison 2020 年 11 月 30 日
Ok, but this gives the same answer everytime. If another car comes in, it should go into spot 2. Could I put this code inside a while loop so the car changes to car = 2 for the next run?
Zach Harrison
Zach Harrison 2020 年 11 月 30 日
Update: I switched your if statement with a while loop and got rid of the else part, and moved the car = car + 1; into the while loop. This seems to work, thank you

サインインしてコメントする。


David Hill
David Hill 2020 年 11 月 30 日
spot=randi(2,1,20)-1;%I would keep it one dimensional (initial fill of parking spots)
fillorder=randperm(numel(spot));%make fill order as complex as you like
if isequal(nnz(spot),numel(spot))
disp('The parking lot is full');
else
nextspot=fillorder(find(spot(fillorder))==0,1);
spot(nextspot)=1;
end

カテゴリ

Help Center および File ExchangeGraphics Object Properties についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by