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};
string word = get_string("Player 1: ");
int score[26];
int sum=0;
int i=0;
while (word[i]!='\0')//string to alphanum
{
if (isupper(word[i]))
{
word[i]=(int)word[i];
score[i]=word[i]-65;
}
else if (islower(word[i]))
{
word[i]=(int)word[i];
score[i]=word[i]-97;
}
printf("%d\t",score[i]);
i++;
}
printf("\n");
for (int j=0;score[j]!='\0';j++)
{
score[j]=POINTS[score[j]];
printf("%d \t",score[j]);
}
the code works for all the values apart from A\a, for some reason it stops working , ive first converted the input charater array(word[]) into interger array,then tried to link the score array ( represents alphabets position==> A-0,B-1,C-2,..,Z-25) to the POINTS array which represents the scrabble value for each letter (Z-10,A-1)
One problem is that doing arithmetic on the symbol table values like
'A' + 1 == 'B'etc is actually not well-defined or guaranteed to work, save for the symbols'0'to'9'where such a guarantee is made by the C standard.This means that you can't have a look-up score table of 26 scores and calculate the index in that table based on character value subtracted by
'A'(or 65). If CS-50 is saying otherwise, it is bad.Luckily however, mainstream computers have lots of memory these days so we may create a look-up table like this instead:
This is taking up 256 bytes instead of 26 but that's no big deal. We set up each index of the table through so called "designated intializers", the
['A'] =things - this is an easy way to create self-documenting code. Items left out of the array initialization are guaranteed to get set to zero, which is fine in this case.As you noticed, this also eliminated the
isupper/toupperetc run-time checks, if we just set'A'and'a'to the same value. That's an optimization for faster execution speed, at the cost of ROM memory.Usage:
As you can see, there's no need for
scoreto be an array, since we don't really need to know/preserve the information that letter number n gave x points. We just want to know the total score.