Week 2 Scrabble Optimization
I just finished the Scrabble problem from Week 2. Frankly, it took me about a day to wrap my head around it. I think what I did was very unorthodox and unoptimized at all. Can you help me find ways to optimize this code? I know programmers have relatively different solutions for solving things. Need your guys insights! Thank you in advance! Here's mine:
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.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};
char ALPHABET[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
int compute_score(string word);
const int N = 2;
int main(void)
{
// Get input words from players
string playerWord[N];
int playerNumber = 1;
for (int i = 0; i < N; i++)
{
playerWord[i] = get_string("Player %i: ", playerNumber);
playerNumber++;
}
// Score both words
int score[N];
score[0] = compute_score(playerWord[0]);
score[1] = compute_score(playerWord[1]);
// TODO: Print the winner
if (score[0] > score[1])
{
printf("Player 1 wins!\n");
}
else if (score[1] > score[0])
{
printf("Player 2 wins!\n");
}
else
{
printf("Tie!\n");
}
}
int compute_score(string word)
{
// TODO: Compute and return score for string
int n = strlen(word);
int sum = 0;
for (int i = 0; i < n; i++)
{
int counter = 0;
word[i] = toupper(word[i]);
for (int j = 0; j < 27; j++)
{
if (word[i] >= 'A' && word[i] <= 'Z')
{
if (word[i] == ALPHABET[j])
{
sum += POINTS[counter];
break;
}
counter++;
}
else
{
break;
}
}
}
return sum;
}