The challenge

Two red beads are placed between every two blue beads. There are N blue beads. After looking at the arrangement below work out the number of red beads.

@ @@ @ @@ @ @@ @ @@ @ @@ @

Implement count_red_beads(n) (countRedBeads(n)) so that it returns the number of red beads.
If there are less than 2 blue beads return 0.

The solution in C

Option 1:

1
2
3
4
int countRedBeads(n) {
  if(n<=1) return 0;
  return 2*(n-1);
}

Option 2:

1
2
3
4
5
6
7
int countRedBeads(n) {
  if (n < 2) {
    return 0;
  } else {
    return n + (n-2);
  }
}

Option 3:

1
2
3
4
int countRedBeads(n)
{
  return n<2 ? 0 : 2*n-2;
}

Test cases to validate our solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#include <criterion/criterion.h>

int countRedBeads (int n);

Test(sample_tests, should_pass_all_the_tests_provided)
{
    cr_assert_eq(countRedBeads(0), 0);
    cr_assert_eq(countRedBeads(1), 0);
    cr_assert_eq(countRedBeads(3), 4);
    cr_assert_eq(countRedBeads(5), 8);
}