How to check a repeat value inside a for loop?

2 ビュー (過去 30 日間)
Marinna Lorence
Marinna Lorence 2015 年 11 月 27 日
回答済み: Image Analyst 2015 年 11 月 27 日
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

回答 (2 件)

Geoff Hayes
Geoff Hayes 2015 年 11 月 27 日
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;
Note that you can then check to see if there are any un-opened cases using all as
if all(caseStates)
fprintf('There are no unopened cases!\n');
end

Image Analyst
Image Analyst 2015 年 11 月 27 日
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

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by