Skip to content

Project Euler Problem 89

November 9, 2012

Solving Problem 89 was easy. In fact, solving the problem does not require any conversion of the source data as the question is how much shorter the converted numbers are going to be. It can be derived from the problem outline that cases for the length reduction are IIII, VIIII, XXXX, LXXXX, CCCC, and DCCCC. As each reduction of these yields just two digits, correspondent reductions are going to be 2,3,2,3,2,3. Accumulating all reductions, being applied from the beginning of the file each time for the closest available reduction to the end will be the sought solution. Very simple recursive function reduce does exactly this.

open System.IO

let rec reduce saved (roman: string)  =
    match ([| "IIII"; "VIIII"; "XXXX"; "LXXXX"; "CCCC"; "DCCCC" |]
        |> (fun x -> (x, roman.IndexOf(x)))
        |> Array.filter (fun (x, i) -> i >= 0)) with
    | [||] -> saved
    | _ as a -> a |> Array.minBy(fun (x,i) -> i)
                  |> fun (x,i) -> reduce (saved + x.Length - 2) (roman.Substring(i + x.Length))

let problem089() =
    File.ReadAllText( @"..\..\..\Datafiles\") |> reduce 0

From → Project Euler

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: