Last active
March 19, 2016 12:38
-
-
Save DavidBrower/d51d6b85503b541fca3c to your computer and use it in GitHub Desktop.
Finding a Palindrome Based on Jake Harry's Algorithm
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
//Based on Jake Harry's article on generating palindromes http://www.p196.org/papers10.html | |
open System | |
let getDistanceFromNextHundred n = | |
100 - (n % 100) | |
let getTensForAddition n = | |
Math.Ceiling(float n/ 10.) * 10. | |
|> int | |
let getNewNum n = | |
getDistanceFromNextHundred n | |
|> getTensForAddition | |
|> (+) n | |
let rec sumDigits n = | |
if n = 0 then 0 | |
else n % 10 + sumDigits(n / 10) | |
let reverseDigits = | |
Seq.unfold(fun x->if x=0 then None else Some(x%10,x/10)) | |
>> Seq.toList | |
>> List.reduce(fun a b ->a*10+b) | |
let generatePalindrome n = | |
let firstDigitSum = sumDigits n | |
let newNum = getNewNum n | |
let secondDigitSum = sumDigits newNum | |
let difference = firstDigitSum - secondDigitSum | |
let palindromeHalf = newNum + difference | |
palindromeHalf + reverseDigits palindromeHalf | |
Seq.initInfinite generatePalindrome | |
|> Seq.takeWhile (fun x -> x < 999 * 999) | |
|> Seq.max |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is producing the wrong result: 920029.