-
Notifications
You must be signed in to change notification settings - Fork 0
/
7_kyu_Simple_Fun_238_Tennis_Game_Points.c
56 lines (54 loc) · 2.69 KB
/
7_kyu_Simple_Fun_238_Tennis_Game_Points.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*Your friend has invited you to watch a tennis match at a local sports club. Since tennis isn't your favorite sport, you get bored right at the start of the first game and start looking for something to keep yourself entertained.
Noticing the scoreboard, you realize you don't even know how many points have been won since the game started, so you decided to calculate this number.
Given the current score, your goal is to find the number of points won in the current game.
If you are not familiar with tennis rules, here's a short description of its scoring system.
Score calling is unique in tennis: each point has a corresponding call that is different from its point value. The table of points won and corresponding calls is given below.
+----------------------+--------------------+
| Number of points won | Corresponding call |
+----------------------+--------------------+
| 0 | "love" |
+----------------------+--------------------+
| 1 | "15" |
+----------------------+--------------------+
| 2 | "30" |
+----------------------+--------------------+
| 3 | "40" |
+----------------------+--------------------+
There's an additional rule to remember: when players are tied by one or two points, the score is described as "15-all" and "30-all", respectively.
It's guaranteed that no more than 5 points have been won so far, and the game is not over yet. It is also guaranteed that at least one point has been won.
Input/Output
[input] string score
A string in the format <p1>-<p2> representing a valid score, where <p1> is the first player's score, and <p2> is the second player's score.
[output] an integer
The number of points won so far.
Example
For score = "15-40", the output should be 4.
The first player won 1 point, and the second 3, so 1 + 3 = 4 points have been won.
For score = "30-all", the output should be 4.
The players have won 2 points each.*/
#include <string.h>
#include <stdlib.h>
unsigned tennis_game_points(const char* score) {
char* s = malloc(strlen(score) + 1);
strcpy(s, score);
const char* calls[4] = {"love", "15", "30", "40"};
unsigned pts[2] = {0, 0};
int i = 0;
if (pts[0] == pts[1]) {
if (strcmp(s, "15-all") == 0) return 2;
if (strcmp(s, "30-all") == 0) return 4;
if (strcmp(s, "40-all") == 0) return 6;
}
char* token = strtok((char*)s, "-");
while (token != NULL) {
for (int j = 0; j < 4; ++j) {
if (strcmp(token, calls[j]) == 0) {
pts[i] = j;
break;
}
}
token = strtok(NULL, "-");
++i;
}
return pts[0] + pts[1];
}