Skip to content

Instantly share code, notes, and snippets.

@Thecentury
Created August 1, 2016 17:15
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 Thecentury/1a8ef83676ce9557fa365e1717ac1c1e to your computer and use it in GitHub Desktop.
Save Thecentury/1a8ef83676ce9557fa365e1717ac1c1e to your computer and use it in GitHub Desktop.
let coins = [50;22;19;17;10;7;5;3;2;1;1;1;1;1] |> List.sortBy (fun x -> -x)
let rec take coins coin =
match coins with
| x::xs when x > coin -> take xs coin
| x::xs when x < coin -> []
| x::xs when x = coin -> xs
| [] -> []
let rec change (coins:list<int>) (amt:int) =
let less = List.filter (fun x -> x <= amt) coins
match less with
| [] -> [[]]
| _ ->
let unique = less |> Seq.distinct |> Seq.sortDescending |> Seq.toList
let variants = unique |> List.map (fun first ->
let remaining = amt - first
if remaining = 0 then
[[first]]
else
let rest = take coins first
let tails = change rest remaining
tails |> List.filter (fun l -> List.length l > 0) |> List.map (fun t -> first :: t)) |> List.concat
variants
let dumpToString ways =
let strs = ways |> List.map (fun x1 -> String.Join ("; ", (x1 |> List.map (fun xx -> xx.ToString()) |> List.toArray)))
strs.Dump()
change coins 54 |> dumpToString
change coins 55 |> dumpToString
change coins 56 |> dumpToString
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment