Skip to content

Instantly share code, notes, and snippets.

@jarlestabell
jarlestabell / Problem5_performant.fs
Created May 15, 2015 20:18
This one is quite fast. (Except for the printing, it runs in less than a microsecond)
let calcExpr digitCount n=
let rec innerCalc n current=
if current>digitCount then "" else [|" - "; ""; " + "|].[n%3] + string current + innerCalc (n/3) (current+1)
"1" + innerCalc n 2
let eval digitCount n=
let rec innerCalc n current (partialsum, partialnumber)=
if current>digitCount then partialsum + partialnumber
else
let nextPartials = if n % 3 = 1 then (partialsum, partialnumber * 10 + (current * (sign partialnumber)))
let calcExpr n =
let rec innerCalcExpr n current last=
if current>last then "" else [|""; "+"; "-"|].[n%3] + string current + innerCalcExpr (n/3) (current+1) last
"1" + innerCalcExpr n 2 9
let rec sum = function
|(op::h::t) -> (int (op+h)) + sum t
| _ -> 0
let eval text = sum ("+" :: (System.Text.RegularExpressions.Regex.Split(text,@"(\+)|(-)") |> List.ofArray))
@jarlestabell
jarlestabell / Problem5.fs
Last active August 29, 2015 14:20
F# alternative solution to these ones: http://blog.bjartwolf.com/?p=4272
type Expr = Number of int | Plus of Expr * int | Minus of Expr * int
let rec eval = function
| Number n -> n
| Plus(e, n) -> (eval e) + n
| Minus(e, n) -> (eval e) - n
let rec exprAsString = function
| Number n -> n.ToString()
| Plus(e, n) -> sprintf "%s + %d" (exprAsString e) n