CS50 Lab 2: Scrabble

👀 1 min read 👀

大家好,我是 Cindy,最近跟同事小夥伴相約一起看 CS50 的課程,CS50 (Introduction to Computer Science)是一堂美國哈佛大學知名的通識課程,完全免費,在 edxyoutubeCS50-Study-Group github 都可以非常容易地看到。

這篇文章是我練習寫 Week 2 的作業(因為不知道要放在哪裡,才不會以後找不到,所以就決定放在部落格啦),歡迎大家有更好的解法可以一起討論唷~

題目:Lab 2: Scrabble

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
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

// Points assigned to each letter of the alphabet
int POINTS[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};

int compute_score(string word);

int main(void)
{
// Get input words from both players
string word1 = get_string("Player 1: ");
string word2 = get_string("Player 2: ");

// Score both words
int score1 = compute_score(word1);
int score2 = compute_score(word2);

// Print the winner
if (score1 > score2)
{
printf("Player 1 wins!\n");
} else if (score1 < score2)
{
printf("Player 2 wins!\n");
} else
{
printf("Tie!\n");
}
}

int compute_score(string word)
{
// Compute and return score for string
int points = 0;
for (int i = 0, n = strlen(word); i < n; i++)
{
if (isupper(word[i]))
{
points += POINTS[word[i] - 65];
} else if (islower(word[i]))
{
points += POINTS[word[i] - 97];
}
}
return points;
}