Consider a game where 2 players ($A$ and $B$) each has a bunch of cards, and play alternately.
Playing a shot for a player ($A$) consists in taking the first 2 cards from his bunch and comparing them. We distinguish the following two cases:
- Both cards are equal: ($A$) wins the sum of both cards and both cards are removed.
- Both cards are distinct: ($A$) loses the amount of the largest card. He removes it and places the other card (smallest one) down the bunch of his opponent ($B$).
A party is a succession of shots according to the above described model ($A$ plays the first shot). The game ends when a player ($A$ or $B$) has not enough cards to play. The winner is the one who has the most points; he earns the difference between his points and those of his opponent.
We model a player by:
\(\texttt{typedef struct \{ $\cdots$ Cards ; int gain ; \} player ;}\)
- Complete the previous declaration by the adequate ADT.
In the following, you must use only the ADT operations mentioned in 1. - Write a function shot that takes as input 2 players and updates them after a shot of the first player. The function returns 0 if the first player cannot play.
- Write a function party that simulates a party by taking as input 2 players, returns the winning player and the total amount of points he earns (difference between his points and those of his opponent).
- Without performing calculations, give the complexity of the previous function in terms of number of shots, and justify your answer.
Difficulty level
This exercise is mostly suitable for students
1. A and B can be considered as queues
2.
int shot(player *A, player *B) {
element eA1, eA2 ; int d;
if (!Front(A->Cards,&eA1) || !Dequeue(&(A->Cards) ||
!Front(A->Cards,&eA2) || !Dequeue(&(A->Cards)) return 0 ;
if (eA1 == eA2) A->gain+= 2 * eA1 ;
else {
A->gain -= max(eA1,eA2) ;
Enqueue(&(B->Cards),min(eA1,eA2)) ;
}
return 1 ;
}
3.
int party(player *A, player *B, char *winner)
{ int x ;
while (shot(A,B) && shot(B,A)) ;
if (x=(A->gain-B->gain) > 0) {*winner = 'A' ; return x ;}
else if (x<0) {*winner = 'B' ; return -x ;}
else { *winner ='N' ; /* Match Nul */ return 0 ;}
}
4. order of the number of cards
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Removing a sequence of 3 characters from a string