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:

1
2
3
4
5
6
7
8
int word_score (const char *word) {
  int x = 0;
  
  while (*word)
    x += *word++ - 'a' + 1;
  
  return x;
}

Option 2:

1
2
3
4
5
6
7
#include <string.h>
int word_score (const char *word) {
  int sum = 0 ,len = strlen(word);
  for(int i = 0; i< len; i++)
    sum += word[i] - 'a' + 1;
  return sum;
}

Option 3:

1
2
3
4
5
6
7
int word_score(const char *word) {
    int sum = 0;
    while(*word) {
        sum += *word++ - 96;
    }
    return sum;
}

Test cases to validate our solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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
	);
}