How to check a repeat value inside a for loop?
조회 수: 2 (최근 30일)
이전 댓글 표시
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
답변 (2개)
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;
if all(caseStates)
fprintf('There are no unopened cases!\n');
end
댓글 수: 0
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!