Skip to content

Solving Love vs Friendship in C

The challenge

If a = 1, b = 2, c = 3 ... z = 26

Then l + o + v + e = 54

and f + r + i + e + n + d + s + h + i + p = 108

So friendship is twice as strong as love ðŸ™‚

Your task is to write a function which calculates the value of a word based off the sum of the alphabet positions of its characters.

The input will always be made of only lowercase letters and will never be empty.

The solution in C

Option 1:

int word_score (const char *word) { int x = ; while (*word) x += *word++ - 'a' + 1; return x; }
Code language: C++ (cpp)

Option 2:

#include <string.h> int word_score (const char *word) { int sum = ,len = strlen(word); for(int i = ; i< len; i++) sum += word[i] - 'a' + 1; return sum; }
Code language: C++ (cpp)

Option 3:

int word_score(const char *word) { int sum = ; while(*word) { sum += *word++ - 96; } return sum; }
Code language: C++ (cpp)

Test cases to validate our solution

#include <criterion/criterion.h> static void do_test (const char *word, int expected); Test(kata, basic_tests) { do_test("attitude", 100); do_test("friends", 75); do_test("family", 66); do_test("selfness", 99); do_test("knowledge", 96); } extern int word_score (const char *word); static void do_test (const char *word, int expected) { int actual = word_score(word); cr_assert_eq(actual, expected, "expected %d but got %d for word \"%s\"", expected, actual, word ); }
Code language: C++ (cpp)

See also  pt-online-schema-change Add Index
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x