How many letters would be needed to write all the numbers in words from 1 to 1000?

module Problem17 =
let ones = [|""; "one"; "two"; "three"; "four"; "five"; "six"; "seven"; "eight"; "nine"; "ten"; "eleven"; "twelve"; "thirteen"; "fourteen"; "fifteen"; "sixteen"; "seventeen"; "eighteen"; "nineteen"; "twenty"|] |> Array.map String.length
let tens = [|""; "";"twenty"; "thirty"; "forty"; "fifty"; "sixty"; "seventy"; "eighty"; "ninety"|] |> Array.map String.length
let hundred = [|"hundred"|] |> Array.map String.length
let rec numLength n =
match n with
| n when n <= 20 -> ones.[n]
| n when n < 100 -> tens.[(n/10)] + (numLength (n%10))
| n when n < 1000 && n % 100 = 0 -> ones.[n/100] + hundred.[0]
| n when n < 1000 -> ones.[n/100] + hundred.[0] + String.length "and" + (numLength (n%100))
| n when n = 1000 -> String.length "oneThousand"
| _ -> failwith "Out of range"
let ans = {1..1000} |> Seq.map numLength |> Seq.sum

I was just about to stop working through project Euler, since I hadn’t run across a problem that forced me to learn a new F# feature for a while (which was my motivation for doing this in the first place), and the algorithmic aspect of the problems hasn’t been that interesting, but this problem forced me to use arrays, which I hadn’t used before. I guess I’ll keep going for at least another few problems.

### Like this:

Like Loading...

*Related*