In lab 2 of CS50, the task is to write a program that takes 2 words and calculates the value of each letter in the words(common letters are worth less and rarer letters are worth more) and compares them, then finally shows which word is worth more. The program should also accept symbols, numbers, punctuations, etc. but they are worth 0. And it should also ignore case of the letters. In my program it just ignores letter case, but doesnt accept punctuation marks, numbers, etc, Is there a way to make it work
#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};
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);
// TODO: Print the winner
if(score1 > score2)
{
printf("Player 1 wins!\n");
}
else if (score2 > score1)
{
printf("Player 2 wins!\n");
}
else
{
printf("Tie!\n");
}
}
int compute_score(string word)
{
// TODO: Compute and return score for string
int sum = 0;
int len = strlen(word);
int letter_value[len];
string letters = "abcdefghijklmnopqrstuvwxyz";
//to convert entire word to lower case
for (int w = 0; w <= len; w )
{
word[w] = tolower(word[w]);
}
// to get a array letter_value that has all the letters alphabetic value from 1-26
int m = 0;
for (int w = 0; w < len; m , w )
{
for (int n = 0; word[m] != letters[n]; n )
{
letter_value[m] = n 1;
}
}
//replaces alphabetic letter values in letter_value array into scrabble values
int c = 0;
for (int w = 0; w < len; w )
{
letter_value[w] = POINTS[letter_value[w]];
}
//adds all the elements of array letter_value in variable sum.
for(int w = 0; w < len; w )
{
sum = sum letter_value[w];
}
return(sum);
}
CodePudding user response:
To begin with you probably shouldn't "remove anyother numbers other than letters". Especially since you're not doing correctly and don't recalculate len
afterwards.
Instead let all characters in word
be as they are, and use isalpha
in the calculation loop to check if a character is a letter or not.
And remember to set all unused elements of letter_value
to zero (i.e. for all characters that are not letters).