Software Engineering

Fixing Love vs Friendship in C

Fixing Love vs Friendship in C
Written by admin


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

Your process is to jot down a perform which calculates the worth of a phrase primarily based off the sum of the alphabet positions of its characters.

The enter will at all times be product of solely lowercase letters and can by no means be empty.

The answer in C

Choice 1:

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

Choice 2:

#embrace <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;
}

Choice 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

#embrace <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("pals", 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
	);
}

About the author

admin

Leave a Comment