Avatar of jsks

jsks's solution

to Palindrome Products in the C Track

Published at Aug 21 2019 · 0 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution was written.

Detect palindrome products in a given range.

A palindromic number is a number that remains the same when its digits are reversed. For example, 121 is a palindromic number but 112 is not.

Given a range of numbers, find the largest and smallest palindromes which are products of numbers within that range.

Your solution should return the largest and smallest palindromes, along with the factors of each within the range. If the largest or smallest palindrome has more than one pair of factors within the range, then return all the pairs.

Example 1

Given the range [1, 9] (both inclusive)...

And given the list of all possible products within this range: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 15, 21, 24, 27, 20, 28, 32, 36, 25, 30, 35, 40, 45, 42, 48, 54, 49, 56, 63, 64, 72, 81]

The palindrome products are all single digit numbers (in this case): [1, 2, 3, 4, 5, 6, 7, 8, 9]

The smallest palindrome product is 1. Its factors are (1, 1). The largest palindrome product is 9. Its factors are (1, 9) and (3, 3).

Example 2

Given the range [10, 99] (both inclusive)...

The smallest palindrome product is 121. Its factors are (11, 11). The largest palindrome product is 9009. Its factors are (91, 99).

Getting Started

Make sure you have read the "Guides" section of the C track on the Exercism site. This covers the basic information on setting up the development environment expected by the exercises.

Passing the Tests

Get the first test compiling, linking and passing by following the three rules of test-driven development.

The included makefile can be used to create and run the tests using the test task.

make test

Create just the functions you need to satisfy any compiler errors and get the test to fail. Then write just enough code to get the test to pass. Once you've done that, move onto the next test.

As you progress through the tests, take the time to refactor your implementation for readability and expressiveness and then go on to the next test.

Try to use standard C99 facilities in preference to writing your own low-level algorithms or facilities by hand.

Source

Problem 4 at Project Euler http://projecteuler.net/problem=4

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

test_palindrome_products.c

#include "vendor/unity.h"
#include "../src/palindrome_products.h"

void setUp(void)
{
}

void tearDown(void)
{
}

void check_factors(factor_t * actual, int depth, factor_t expected[])
{
   if (depth == 0) {
      TEST_ASSERT_EQUAL_PTR(NULL, actual);
      return;
   }
   int i;
   int count_ok = 0;
   for (i = 0; i < depth; i++) {
      if (actual == NULL)
         break;
      if ((actual->factor_a == expected[i].factor_a) &&
          (actual->factor_b == expected[i].factor_b))
         count_ok++;
      actual = actual->next;
   }
   TEST_ASSERT_EQUAL_PTR(NULL, actual);
   TEST_ASSERT_EQUAL_INT(depth, count_ok);
}

void test_smallest_palindrome_from_single_digit_factors(void)
{
   product_t *product = get_palindrome_product(1, 9);
   TEST_ASSERT_NOT_NULL(product);
   TEST_ASSERT_EQUAL_INT(1, product->smallest);

   factor_t expected_sm[] = { {1, 1, NULL} };
   check_factors(product->factors_sm, 1, expected_sm);

   free_product(product);
}

void test_largest_palindrome_from_single_digit_factors(void)
{
   TEST_IGNORE();               // delete this line to run test
   product_t *product = get_palindrome_product(1, 9);
   TEST_ASSERT_NOT_NULL(product);
   TEST_ASSERT_EQUAL_INT(9, product->largest);

   factor_t expected_lg[] = { {3, 3, NULL}, {1, 9, NULL} };
   check_factors(product->factors_lg, 2, expected_lg);

   free_product(product);
}

void test_smallest_palindrome_from_double_digit_factors(void)
{
   TEST_IGNORE();               // delete this line to run test
   product_t *product = get_palindrome_product(10, 99);
   TEST_ASSERT_NOT_NULL(product);
   TEST_ASSERT_EQUAL_INT(121, product->smallest);

   factor_t expected_sm[] = { {11, 11, NULL} };
   check_factors(product->factors_sm, 1, expected_sm);

   free_product(product);
}

void test_largest_palindrome_from_double_digit_factors(void)
{
   TEST_IGNORE();               // delete this line to run test
   product_t *product = get_palindrome_product(10, 99);
   TEST_ASSERT_NOT_NULL(product);
   TEST_ASSERT_EQUAL_INT(9009, product->largest);

   factor_t expected_lg[] = { {91, 99, NULL} };
   check_factors(product->factors_lg, 1, expected_lg);

   free_product(product);
}

void test_smallest_palindrome_from_triple_digit_factors(void)
{
   TEST_IGNORE();               // delete this line to run test
   product_t *product = get_palindrome_product(100, 999);
   TEST_ASSERT_NOT_NULL(product);
   TEST_ASSERT_EQUAL_INT(10201, product->smallest);

   factor_t expected_sm[] = { {101, 101, NULL} };
   check_factors(product->factors_sm, 1, expected_sm);

   free_product(product);
}

void test_largest_palindrome_from_triple_digit_factors(void)
{
   TEST_IGNORE();               // delete this line to run test
   product_t *product = get_palindrome_product(100, 999);
   TEST_ASSERT_NOT_NULL(product);
   TEST_ASSERT_EQUAL_INT(906609, product->largest);

   factor_t expected_lg[] = { {913, 993, NULL} };
   check_factors(product->factors_lg, 1, expected_lg);

   free_product(product);
}

void test_smallest_palindrome_from_four_digit_factors(void)
{
   TEST_IGNORE();               // delete this line to run test
   product_t *product = get_palindrome_product(1000, 9999);
   TEST_ASSERT_NOT_NULL(product);
   TEST_ASSERT_EQUAL_INT(1002001, product->smallest);

   factor_t expected_sm[] = { {1001, 1001, NULL} };
   check_factors(product->factors_sm, 1, expected_sm);

   free_product(product);
}

void test_largest_palindrome_from_four_digit_factors(void)
{
   TEST_IGNORE();               // delete this line to run test
   product_t *product = get_palindrome_product(1000, 9999);
   TEST_ASSERT_NOT_NULL(product);
   TEST_ASSERT_EQUAL_INT(99000099, product->largest);

   factor_t expected_lg[] = { {9901, 9999, NULL} };
   check_factors(product->factors_lg, 1, expected_lg);

   free_product(product);
}

void test_empty_result_for_smallest_if_no_palindrome_in_the_range(void)
{
   TEST_IGNORE();               // delete this line to run test
   product_t *product = get_palindrome_product(1002, 1003);
   TEST_ASSERT_NOT_NULL(product);
   const char *expected =
       "no palindrome with factors in the range 1002 to 1003";
   TEST_ASSERT_EQUAL_STRING(expected, product->error);

   free_product(product);
}

void test_empty_result_for_largest_if_no_palindrome_in_the_range(void)
{
   TEST_IGNORE();               // delete this line to run test
   product_t *product = get_palindrome_product(15, 15);
   TEST_ASSERT_NOT_NULL(product);
   const char *expected = "no palindrome with factors in the range 15 to 15";
   TEST_ASSERT_EQUAL_STRING(expected, product->error);

   free_product(product);
}

void test_error_result_for_smallest_if_min_is_more_than_max(void)
{
   TEST_IGNORE();               // delete this line to run test
   product_t *product = get_palindrome_product(10000, 1);
   TEST_ASSERT_NOT_NULL(product);
   const char *expected = "invalid input: min is 10000 and max is 1";
   TEST_ASSERT_EQUAL_STRING(expected, product->error);

   free_product(product);
}

void test_error_result_for_largest_if_min_is_more_than_max(void)
{
   TEST_IGNORE();               // delete this line to run test
   product_t *product = get_palindrome_product(2, 1);
   TEST_ASSERT_NOT_NULL(product);
   const char *expected = "invalid input: min is 2 and max is 1";
   TEST_ASSERT_EQUAL_STRING(expected, product->error);

   free_product(product);
}

int main(void)
{
   UnityBegin("test/test_palindrome_products.c");

   RUN_TEST(test_smallest_palindrome_from_single_digit_factors);
   RUN_TEST(test_largest_palindrome_from_single_digit_factors);

   RUN_TEST(test_smallest_palindrome_from_double_digit_factors);
   RUN_TEST(test_largest_palindrome_from_double_digit_factors);

   RUN_TEST(test_smallest_palindrome_from_triple_digit_factors);
   RUN_TEST(test_largest_palindrome_from_triple_digit_factors);

   RUN_TEST(test_smallest_palindrome_from_four_digit_factors);
   RUN_TEST(test_largest_palindrome_from_four_digit_factors);

   RUN_TEST(test_empty_result_for_smallest_if_no_palindrome_in_the_range);
   RUN_TEST(test_empty_result_for_largest_if_no_palindrome_in_the_range);

   RUN_TEST(test_error_result_for_smallest_if_min_is_more_than_max);
   RUN_TEST(test_error_result_for_largest_if_min_is_more_than_max);

   UnityEnd();
   return 0;
}

src/palindrome_products.c

#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>

#include "palindrome_products.h"

static bool is_palindrome(int x) {
  int digit, number = x, n = 0;

  while (x > 0) {
    digit = x % 10;
    n = n * 10 + digit;

    x /= 10;
  }

  return number == n;
}

static int push_factors(factor_t **head, int x, int y) {
  factor_t *p;
  if (!(p= malloc(sizeof(factor_t))))
    return -1;

  p->factor_a = x;
  p->factor_b = y;

  p->next = *head;
  *head = p;

  return 0;
}

static void free_factors(factor_t **head) {
  if (!(*head))
    return;

  factor_t *p = *head, *next;

  while (p) {
    next = p->next;
    free(p);
    p = next;
  }

  *head = NULL;
}

product_t *get_palindrome_product(int x, int y) {
  product_t *p;
  if (!(p = calloc(1, sizeof(product_t))))
    goto err;

  if (x > y) {
    asprintf(&p->error, "invalid input: min is %d and max is %d", x, y);
    if (!p->error)
      goto err;

    return p;
  }

  // This will really not be winning any speed contests...
  for (int i = x; i <= y; i++) {
    for (int j = i; j <= y; j++) {
      int prod = i * j;
      if (!is_palindrome(prod))
        continue;

      if (p->smallest == 0 || prod <= p->smallest) {
        if (prod != p->smallest) {
          p->smallest = prod;
          free_factors(&p->factors_sm);
        }

        if (push_factors(&p->factors_sm, i, j) == -1)
          goto err;
      } else if (p->largest == 0 || prod >= p->largest) {
        if (prod != p->largest) {
          p->largest = prod;
          free_factors(&p->factors_lg);
        }

        if (push_factors(&p->factors_lg, i, j) == -1)
          goto err;
      }
    }
  }

  if (p->smallest == 0 && p->largest == 0) {
    asprintf(&p->error, "no palindrome with factors in the range %d to %d", x, y);
    if (!p->error)
      goto err;
  }

  return p;

 err:
  free_product(p);
  return NULL;
}

void free_product(product_t *p) {
  if (!p)
    return;

  free_factors(&p->factors_lg);
  free_factors(&p->factors_sm);
  free(p->error);

  free(p);
}

src/palindrome_products.h

#ifndef PALINDROME_PRODUCTS
#define PALINDROME_PRODUCTS

typedef struct factor {
  int factor_a;
  int factor_b;
  struct factor* next;
} factor_t;

typedef struct {
  int largest;
  int smallest;
  char *error;
  factor_t *factors_lg;
  factor_t *factors_sm;
} product_t;


product_t *get_palindrome_product(int x, int y);
void free_product(product_t *);

#endif

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?