3 people like it.
Like the snippet!
Largest palindrome made from the product of two n-digit numbers
A generalised version of the solution to the fourth Project Euler problem - Largest palindrome product, using sequences.
The key to understanding this code is how "Seq.map (fun x -> (Seq.map (fun y -> x * y) baseSeq)) baseSeq" generates a sequence of sequences that contains the products of all possible combinations of two n-digit numbers.
"Seq.map (fun x -> (Seq.map (fun y -> x * y) {1..3})) {1..3}" will generate:
seq [seq [1; 2; 3]; seq [2; 4; 6]; seq [3; 6; 9]]
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
|
let numDigits = 3
if (numDigits < 1) then failwith "Number of digits must be at least 1"
let lowestNumDigitNumber = pown 10 (numDigits - 1)
let highestNumDigitNumber = (pown 10 numDigits) - 1
let baseSeq = {lowestNumDigitNumber..highestNumDigitNumber}
let reverse (t : string) =
new string(t.ToCharArray() |> Array.rev)
let isPalindrome t = reverse (string t) = string t
Seq.map (fun x -> (Seq.map (fun y -> x * y) baseSeq)) baseSeq
|> Seq.concat
|> Seq.filter isPalindrome
|> Seq.max
|> printfn "Largest palindrome made from the product of two %d-digit numbers: %A" numDigits
|
val numDigits : int
Full name: Script.numDigits
val failwith : message:string -> 'T
Full name: Microsoft.FSharp.Core.Operators.failwith
val lowestNumDigitNumber : int
Full name: Script.lowestNumDigitNumber
val pown : x:'T -> n:int -> 'T (requires member get_One and member ( * ) and member ( / ))
Full name: Microsoft.FSharp.Core.Operators.pown
val highestNumDigitNumber : int
Full name: Script.highestNumDigitNumber
val baseSeq : seq<int>
Full name: Script.baseSeq
val reverse : t:string -> string
Full name: Script.reverse
val t : string
Multiple items
val string : value:'T -> string
Full name: Microsoft.FSharp.Core.Operators.string
--------------------
type string = System.String
Full name: Microsoft.FSharp.Core.string
System.String.ToCharArray() : char []
System.String.ToCharArray(startIndex: int, length: int) : char []
module Array
from Microsoft.FSharp.Collections
val rev : array:'T [] -> 'T []
Full name: Microsoft.FSharp.Collections.Array.rev
val isPalindrome : t:int -> bool
Full name: Script.isPalindrome
val t : int
module Seq
from Microsoft.FSharp.Collections
val map : mapping:('T -> 'U) -> source:seq<'T> -> seq<'U>
Full name: Microsoft.FSharp.Collections.Seq.map
val x : int
val y : int
val concat : sources:seq<#seq<'T>> -> seq<'T>
Full name: Microsoft.FSharp.Collections.Seq.concat
val filter : predicate:('T -> bool) -> source:seq<'T> -> seq<'T>
Full name: Microsoft.FSharp.Collections.Seq.filter
val max : source:seq<'T> -> 'T (requires comparison)
Full name: Microsoft.FSharp.Collections.Seq.max
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
More information