generate a random seat number loop while the generated seat is unavailable generate another random seat number end loop change seat to unavailable in matlab

Here's an example code that generates a random seat number within a given range and checks if the seat is available or not. If the seat is not available, it generates another random seat number until it finds an available seat. Once an available seat is found, it marks it as unavailable:

main.m
% Set the range of seat numbers and initialize availability
num_seats = 100;
seats_available = true(1, num_seats);

% Generate a random seat number and check availability
while true
    seat_num = randi(num_seats);  % Random integer between 1 and num_seats
    if seats_available(seat_num)
        seats_available(seat_num) = false;  % Mark seat as unavailable
        break;  % Exit loop if available seat is found
    end
end

disp("Assigned seat number: " + string(seat_num));
480 chars
15 lines

The code works by creating a logical array seats_available with true values for all seats. Then it generates a random seat number with the randi function and checks if the corresponding element in seats_available is true. If the seat is available, it marks it as unavailable and exits the loop with the assigned seat number. If the seat is not available, it generates another random seat number and tries again.

Note that this code assumes that there is no other code that modifies the seats_available array. If there is, you'll need to make sure that the array stays synchronized with the actual availability of the seats.

gistlibby LogSnag