Skip to content

Instantly share code, notes, and snippets.

@vbe0201
Last active November 16, 2020 10:01
Show Gist options
  • Save vbe0201/2ff28a9383016d11aeb21d998ec7c32f to your computer and use it in GitHub Desktop.
Save vbe0201/2ff28a9383016d11aeb21d998ec7c32f to your computer and use it in GitHub Desktop.
baby-cpp reimplementation - decompetition.io
/* decompetition.io tiny-cpp reimplementation */
#include <iostream>
#include <string>
#include <vector>
/* Function prototypes */
bool check(const std::string& hand, const std::string& word);
int score(const std::string& word);
int main(int argc, char **argv) {
/* If the program is not invoked with two strings as arguments, error out. */
if (argc != 3) {
std::cerr << "USAGE: ./clabbers [hand] [word]" << std::endl;
return 1;
}
std::string hand(argv[1]);
std::string word(argv[2]);
/* Ensure that the supplied hand and word strings are allowed. */
if (!check(hand, word)) {
std::cout << "Invalid." << std::endl;
return 2;
} else {
/* Compute the score of the player and print it. */
int player_score = score(word);
const char *multi = (player_score == 1) ? "s" : "";
std::cout << player_score << " point" << multi << "." << std::endl;
}
return 0;
}
/* Validates the supplied hand and word strings. */
bool check(const std::string& hand, const std::string& word) {
std::vector<int> count_table(26, 0);
/* Validate the characters in the hand string. */
for (char cur_char : hand) {
if (!isalpha(cur_char))
return false;
count_table[toupper(cur_char) - 'A'] += 1;
}
/* Validate the characters in the word string. */
for (char cur_char : word) {
if (!isalpha(cur_char))
return false;
if ((count_table[toupper(cur_char) - 'A'] -= 1) < 0)
return false;
}
return true;
}
/* Computes the points that the supplied word scores. */
int score(const std::string& word) {
int score = 0;
const std::vector<int> score_table {
1, 3, 3, 2, 1, 4, 2, 4, 1,
8, 5, 1, 3, 1, 1, 3, 10, 1,
1, 1, 1, 5, 4, 8, 3, 10,
};
/* Sum up the score values corresponding to each char in the word. */
for (char cur_char : word) {
score += score_table[toupper(cur_char) - 'A'];
}
return score;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment