Skip to content

Instantly share code, notes, and snippets.

@davidgrenier
Forked from ssboisen/count_change.fs
Created September 19, 2013 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidgrenier/6623773 to your computer and use it in GitHub Desktop.
Save davidgrenier/6623773 to your computer and use it in GitHub Desktop.
open System
open System.Diagnostics
let inline (|LessThan|_|) n = function
| x when x < n -> Some()
| _ -> None
let rec cc amount coins =
match amount, coins with
| 0, _ -> 1
| _, [] | LessThan 0, _ -> 0
| _, c::cs -> cc amount cs + cc (amount - c) coins
[<EntryPoint>]
let main argv =
let stopWatch = Stopwatch.StartNew()
let x = cc 100 [1;2;3;4;5;6;7]
printfn "Result: %i elapsed: %g ms" x stopWatch.Elapsed.TotalMilliseconds
Console.ReadLine() |> ignore
0
@davidgrenier
Copy link
Author

A tail recursive version that would work with very long lists (but take a lifetime) seems to be 5 times slower. Clearly unnecessary but worth having a look at.

let cc =
    let rec cc kont amount coins =
        match amount, coins with
        | 0, _ -> kont 1
        | _, [] | LessThan 0, _ -> kont 0
        | _, c::cs -> cc (fun v -> cc ((+) v >> kont) (amount - c) coins) amount cs

    cc id

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment