In: Computer Science
You have 21 cards written from 1 to 21. The number K is inputted from a command window (using input command). First, please shuffle these 21 cards such that the sequence becomes random (using rand command). You need to make a function of New_Cards=shuffle(Orig_Card), where New_Cards is a 1X21 vector that has random sequence of the cards (Ex. New_Cards=[ 14 7 21 6….. 9 1 3 5 8]). When the first even number is greater than K, you should print in the command window saying that ‘You win!’, otherwise ‘You lost!’. K should be set as a global variable in the main cell. Please create a function of Output = game(New_Cards). Output is 1 when the first even number is greater than K, and it is 0 when the first even number is less than K.(Using Matlab)
Screenshot
------------------------------------------------------------------------------------
Program
Functions
%function to set a global variable
function setGlobalK(value)
global k
k = value;
end
%Function to get global value
function k = getGlobalK
global k
k = k;
end
%Function to shuffle the cards
function New_Cards=shuffle(Orig_Card)
New_Cards=Orig_Card;
New_Cards=New_Cards(randperm(length(New_Cards)));
end
%Function to check condition
function Output = game(New_Cards)
evens=New_Cards(mod(New_Cards,2)==0);
if evens(1)>getGlobalK
Output=1;
else
Output=0;
end
end
Test
Orig_Card=1:21;
New_Cards=shuffle(Orig_Card);
setGlobalK(input('Enter value of k: '))
Output = game(New_Cards);
if(Output)
disp('You win!');
else
disp('You lost!');
end
-------------------------------------------------------
Output
Enter value of k: 10
You win!