<?php

/**
 * Project Euler Problem 4: Largest palindrome product
 * 
 * A palindromic number reads the same both ways. The largest palindrome made 
 * from the product of two 2-digit numbers is 9009 = 91 × 99.
 * 
 * Find the largest palindrome made from the product of two 3-digit numbers.
 * 
 * Problem: https://p...content-available-to-author-only...r.net/problem=4
 * Solution: https://g...content-available-to-author-only...b.com/potherca-blog/ProjectEuler/blob/master/src/PHP/Solutions/Problem004.php
 * Live code: https://i...content-available-to-author-only...e.com/MwUCwn
 */
namespace Potherca\ProjectEuler\Solutions\Problem004
{
    use Potherca\ProjectEuler\Calculators\PalindromeProductCalculator as Calculator;

	$digits = 3;
    
    $solution = (new Calculator())->getHighestPalindromeForProduct($digits);
    
    echo $solution;
}

namespace Potherca\ProjectEuler\Calculators
{
    class PalindromeProductCalculator
    {
        final public function getHighestPalindromeForProduct(int $digits): int
        {
        	$palindromes = $this->getPalindromesForProduct($digits);

        	return end($palindromes);
        }

        final public function getPalindromesForProduct(int $digits): array
        {
        	$low = 10 ** ($digits - 1);
        	$high = (10 ** $digits) - 1;

        	return $this->getPalindromesForRange($low, $high);
        }

        final public function getPalindromesForRange(int $low, int $high): array
        {
			$palindromes = [];

			$numbers = range($low, $high);

			foreach ($numbers as $left) {
				foreach ($numbers as $right) {
					$number = $left * $right;

					$reverse = (int) strrev($number);

					if (
						$reverse === $number
						&& ! in_array($number, $palindromes)
					) {
						$palindromes[] = $number;
					}
				}
			}

			sort($palindromes);

			return $palindromes;
        }
    }
}
