How to check a repeat value inside a for loop?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I'm attempting to build Deal or No Deal and for round one a user has to pick 6 cases, I'm stuck on how to check every value they are entering is not a repeat. In this UserCase is the original case they pick to be theirs, as in the game show. I know I have to add another loop somewhere in the mix but I have been stuck on this for hours with no progress.
if true
% code
end
Round1=[];
for K=1:6
Case1=input('Choose a case: ');
while Case1<1 || Case1>26 || mod(Case1,1)~=0 || Case1==UserCase
Case1=input('Error: Case already chosen, please choose another: ');
end
Round1=[Round1, Case1];
end
0 Kommentare
Antworten (2)
Geoff Hayes
am 27 Nov. 2015
Marinna - you could create an array to keep track of which cases have been chosen. For example, you could keep track of the state of each case: 0 (false) for not opened, and 1 (true) for opened. Something like
caseStates = logical(zeros(26,1));
Then, whenever the user chooses a new case via
chosenCase=floor(input('Choose a case: '));
while chosenCase < 1 || chosenCase > 26 || caseStates(chosenCase) == true
chosenCase=floor(input('Error: invalid case. Choose a new case: '));
end
caseStates(chosenCase) == true;
if all(caseStates)
fprintf('There are no unopened cases!\n');
end
0 Kommentare
Image Analyst
am 27 Nov. 2015
Try this:
% Define call array for the menu() function.
cases = {'1', '2', '3', '4', '5', '6'}
% Define a vector of what cases were picked.
used = false(1, length(cases))
% Let user pick all of the 6 cases.
for k = 1 : 6
% Let user pick a case.
button = menu('Choose a case', cases);
% for next time, remove this case from consideration.
if button > 0
% User clicked a valid button.
cases(button) = [];
% Let user quit if they want to.
message = sprintf('Do you want to continue');
buttonText = questdlg(message, 'Continue?', 'Yes', 'No', 'Yes');
drawnow; % Refresh screen to get rid of dialog box remnants.
if strcmpi(buttonText, 'No')
return;
else
end
else
% User clicked white X on red square in upper right of title bar.
% They want to quit
break;
end
end
0 Kommentare
Siehe auch
Kategorien
Mehr zu Startup and Shutdown finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!