Created
March 30, 2015 21:31
-
-
Save YanivHaramati/49a3eb9792dc55bfca2a to your computer and use it in GitHub Desktop.
Largest palindrome product
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getPalindromes(from, to) { | |
var palindromes = []; | |
for (var n = from; n <= to; n++) { | |
if (isPalindrome(n)) palindromes.push(n); | |
} | |
return palindromes; | |
} | |
function isPalindrome(n) { | |
var nCArray = n.toString().split(''); | |
for (var i = 0; i < nCArray.length; i++) { | |
if (nCArray[i] != nCArray[nCArray.length - 1 - i]) return false; | |
} | |
return true; | |
} | |
function getMaxPalindromeWith2KDigitFactors(k) { | |
var low = parseInt("1" + Array.apply(null, Array(k - 1)).map(function (_, i) { return "0"; }).join('')); | |
var high = parseInt("9" + Array.apply(null, Array(k - 1)).map(function (_, i) { return "9"; }).join('')); | |
var palindromes = getPalindromes(Math.pow(low,2), Math.pow(high,2)); | |
var kDigitNumbers = Array.apply(null, Array(high - low + 1)).map(function(_, i) { return low + i; }); | |
var candidates = []; | |
for (var pi = 0; pi < kDigitNumbers.length; pi++) { | |
for (var pj = 0; pj < kDigitNumbers.length; pj++) { | |
var n = kDigitNumbers[pi] * kDigitNumbers[pj]; | |
if (palindromes.indexOf(n) >= 0) { | |
candidates.push(n); | |
} | |
} | |
} | |
return Math.max.apply(null, candidates); | |
} | |
function test(actual, expected, err) { | |
if (actual.constructor === Array && expected.constructor === Array) { | |
if (actual.length === expected.length && | |
actual.every(function (e, i) { | |
return e === expected[i]; | |
})) console.log("SUCCESS"); | |
else err(actual, expected); | |
} | |
else if (actual === expected) console.log("SUCCESS"); | |
else err(actual, expected); | |
} | |
function errMsg(actual, expected) { | |
console.error("ERROR. Found: " + actual + " but expected: " + expected); | |
} | |
test(getMaxPalindromeWith2KDigitFactors(3), 906609, errMsg); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
project euler problem 4