HomeSoftware EngineeringFixing Love vs Friendship in C

Fixing Love vs Friendship in C


The problem

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 robust as love 🙂

Your activity is to put in writing a perform which calculates the worth of a phrase based mostly off the sum of the alphabet positions of its characters.

The enter will all the time be made from solely lowercase letters and can by no means be empty.

The answer in C

Possibility 1:

int word_score (const char *phrase) {
  int x = 0;
  
  whereas (*phrase)
    x += *phrase++ - 'a' + 1;
  
  return x;
}

Possibility 2:

#embody <string.h>
int word_score (const char *phrase) {
  int sum = 0 ,len = strlen(phrase);
  for(int i = 0; i< len; i++)
    sum += phrase[i] - 'a' + 1;
  return sum;
}

Possibility 3:

int word_score(const char *phrase) {
    int sum = 0;
    whereas(*phrase) {
        sum += *phrase++ - 96;
    }
    return sum;
}

Take a look at instances to validate our resolution

#embody <criterion/criterion.h>

static void do_test (const char *phrase, int anticipated);

Take a look at(kata, basic_tests)
{
  do_test("angle", 100);
  do_test("buddies", 75);
  do_test("household", 66);
  do_test("selfness", 99);
  do_test("data", 96);
}

extern int word_score (const char *phrase);

static void do_test (const char *phrase, int anticipated)
{
	int precise = word_score(phrase);
	cr_assert_eq(precise, anticipated,
		"anticipated %d however obtained %d for phrase "%s"",
		anticipated, precise, phrase
	);
}
RELATED ARTICLES

Most Popular

Recent Comments