Avatar of rasmusrim

rasmusrim's solution

to Palindrome Products in the Java Track

Published at Apr 02 2020 · 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).

Setup

Go through the setup instructions for Java to install the necessary dependencies:

https://exercism.io/tracks/java/installation

Running the tests

You can run all the tests for an exercise by entering the following in your terminal:

$ gradle test

Use gradlew.bat if you're on Windows

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by removing the @Ignore("Remove to run test") annotation.

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.

PalindromeCalculatorTest.java

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.Rule;
import org.junit.rules.ExpectedException;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.SortedMap;
import java.util.stream.Collectors;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

public class PalindromeCalculatorTest {
    private PalindromeCalculator palindromeCalculator;

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Before
    public void setup() {
        palindromeCalculator = new PalindromeCalculator();
    }

    @Test
    public void smallestPalindromeFromSingleDigitFactors() {
        List<List<Integer>> expected = Collections.unmodifiableList(
                Arrays.asList(
                        Arrays.asList(1, 1)
                )
        );
        long expectedValue = 1L;

        SortedMap<Long, List<List<Integer>>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(1, 9);

        checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.firstKey());
    }

    @Ignore("Remove to run test")
    @Test
    public void largestPalindromeFromSingleDigitFactors() {
        List<List<Integer>> expected = Collections.unmodifiableList(
                Arrays.asList(
                        Arrays.asList(1, 9),
                        Arrays.asList(3, 3)
                )
        );
        long expectedValue = 9L;

        SortedMap<Long, List<List<Integer>>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(1, 9);

        checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.lastKey());
    }

    @Ignore("Remove to run test")
    @Test
    public void largestPalindromeFromDoubleDigitFactors() {
        List<List<Integer>> expected = Collections.unmodifiableList(
                Arrays.asList(
                        Arrays.asList(91, 99)
                )
        );
        long expectedValue = 9009L;

        SortedMap<Long, List<List<Integer>>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(10,
                                                                                                                 99);

        checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.lastKey());
    }

    @Ignore("Remove to run test")
    @Test
    public void smallestPalindromeFromDoubleDigitFactors() {
        List<List<Integer>> expected = Collections.unmodifiableList(
                Arrays.asList(
                        Arrays.asList(11, 11)
                )
        );
        long expectedValue = 121L;

        SortedMap<Long, List<List<Integer>>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(10,
                                                                                                                 99);

        checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.firstKey());
    }

    @Ignore("Remove to run test")
    @Test
    public void largestPalindromeFromTripleDigitFactors() {
        List<List<Integer>> expected = Collections.unmodifiableList(
                Arrays.asList(
                        Arrays.asList(913, 993)
                )
        );
        long expectedValue = 906609L;

        SortedMap<Long, List<List<Integer>>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(100,
                                                                                                                 999);

        checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.lastKey());
    }

    @Ignore("Remove to run test")
    @Test
    public void smallestPalindromeFromTripleDigitFactors() {
        List<List<Integer>> expected = Collections.unmodifiableList(
                Arrays.asList(
                        Arrays.asList(101, 101)
                )
        );
        long expectedValue = 10201L;

        SortedMap<Long, List<List<Integer>>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(100,
                                                                                                                 999);

        checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.firstKey());
    }

    @Ignore("Remove to run test")
    @Test
    public void smallestPalindromeFromQuadDigitFactors() {
        List<List<Integer>> expected = Collections.unmodifiableList(
                Arrays.asList(
                        Arrays.asList(1001, 1001)
                )
        );
        long expectedValue = 1002001L;

        SortedMap<Long, List<List<Integer>>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(1000,
                                                                                                                 9999);

        checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.firstKey());
    }

    @Ignore("Remove to run test")
    @Test
    public void largestPalindromeFromQuadDigitFactors() {
        List<List<Integer>> expected = Collections.unmodifiableList(
                Arrays.asList(
                        Arrays.asList(9901, 9999)
                )
        );
        long expectedValue = 99000099L;

        SortedMap<Long, List<List<Integer>>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(1000,
                                                                                                                 9999);

        checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, palindromes.lastKey());
    }

    @Ignore("Remove to run test")
    @Test
    public void emtpyResultSmallestNoPalindromeInRange() {

        SortedMap<Long, List<List<Integer>>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(1002,
                                                                                                                 1003);
        assertTrue(palindromes.isEmpty());
    }

    @Ignore("Remove to run test")
    @Test
    public void emptyResultLargestNoPalindromeInRange() {

        SortedMap<Long, List<List<Integer>>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(15,
                                                                                                                 15);
        assertTrue(palindromes.isEmpty());
    }

    @Ignore("Remove to run test")
    @Test
    public void errorSmallestMinIsMoreThanMax() {

        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("invalid input: min must be <= max");

        SortedMap<Long, List<List<Integer>>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(10000,
                                                                                                                 1);
    }

    @Ignore("Remove to run test")
    @Test
    public void errorLargestMinIsMoreThanMax() {

        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("invalid input: min must be <= max");

        SortedMap<Long, List<List<Integer>>> palindromes = palindromeCalculator.getPalindromeProductsWithFactors(2, 1);
    }



    private void checkPalindromeWithFactorsMatchesExpected(List<List<Integer>> expectedPalindromeFactors,
                                                           long expectedValueOfPalindrome,
                                                           SortedMap<Long, List<List<Integer>>> actualPalindromes,
                                                           long actualValueOfPalindrome) {
        assertNotNull(actualPalindromes);
        assertFalse(actualPalindromes.isEmpty());

        assertEquals(expectedValueOfPalindrome, actualValueOfPalindrome);

        List<List<Integer>> actualPalindromeFactors = actualPalindromes
                .get(actualValueOfPalindrome)
                .stream()
                .sorted((a, b) -> Integer.compare(a.get(0), b.get(0)))
                .collect(Collectors.toList());
        assertEquals(expectedPalindromeFactors, actualPalindromeFactors);
    }
}
import com.sun.source.tree.Tree;

import java.util.*;

public class PalindromeCalculator {
    public SortedMap<Long, List<List<Integer>>> getPalindromeProductsWithFactors(int minNumber, int maxNumber) {

        if (minNumber > maxNumber) {
            throw new IllegalArgumentException("invalid input: min must be <= max");
        }

        TreeMap<Long, List<List<Integer>>> palindromes = new TreeMap<>();

        for (int i = minNumber; i <= maxNumber; i++) {
            for (int j = minNumber; j <= maxNumber; j++) {
                long product = i * j;

                String productAsString = Long.toString(product);


                if (isPalindrom(productAsString)) {
                    List<List<Integer>> factors;
                    if (palindromes.containsKey(product)) {
                        factors = palindromes.get(product);
                    } else {
                        factors = new ArrayList<>();
                    }

                    if (!factors.contains(Arrays.asList(i, j)) && !factors.contains(Arrays.asList(j, i))) {
                        factors.add(Arrays.asList(i, j));
                    }

                    palindromes.put(product, factors);

                }


            }

        }

        TreeMap<Long, List<List<Integer>>> returnValues = new TreeMap<>();

        if (palindromes.size() > 0) {
            returnValues.put(palindromes.firstKey(), palindromes.get(palindromes.firstKey()));
            returnValues.put(palindromes.lastKey(), palindromes.get(palindromes.lastKey()));
        }

        return returnValues;

    }

    private boolean isPalindrom(String productAsString) {
        return productAsString.equals(reverseString(productAsString));
    }

    private String reverseString(String input) {
        byte[] strAsByteArray = input.getBytes();
        byte[] reversed = new byte[strAsByteArray.length];

        for (int i = strAsByteArray.length - 1; i >= 0; i--) {
            reversed[strAsByteArray.length - i - 1] = strAsByteArray[i];
        }

        return new String(reversed);
    }
}

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?