Last active
November 27, 2022 04:06
-
-
Save iboss-ptk/6bbb6993cba9b17b1f208ac96a898188 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
if (score1 > score2) | |
{ | |
printf("Player 1 wins!"); | |
} | |
else if (score2 > score1) | |
{ | |
printf("Player 2 wins!"); | |
} | |
else | |
{ | |
printf("Tie!"); | |
} | |
} | |
int compute_score(string word) | |
{ | |
int score = 0; | |
for (int i = 0; i < strlen(word); i++) | |
{ | |
// what we need is a normalized list of a-z to match points | |
// with "A-Z", int representation (ASCII code) of them are consecutive 65-90 | |
int upper_word = toupper(word[i]); | |
// check if it's within A-Z range, | |
// this includes a-z as well since we have already normalized them | |
// this comparison will compare with it's int representation | |
if (upper_word >= 'A' && upper_word <= 'Z') | |
{ | |
// subtract with charcode of 'A' to get matching points index | |
// that is: | |
// if char is A -> 65 - 65 = 0 | |
// if char is B -> 66 - 65 = 1 | |
// and so on.. | |
int point_index = (int)(upper_word - 'A'); | |
score += POINTS[point_index]; | |
} | |
} | |
return score; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment