How to Solve Simple Beads Count in C

0 min read 135 words

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:

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

Option 2:

int countRedBeads(n) {
  if (n < 2) {
    return 0;
  } else {
    return n + (n-2);
  }
}

Option 3:

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

Test cases to validate our solution

#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);
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags