【问题标题】:Find all Change Combinations (money) in OCaml在 OCaml 中查找所有更改组合(金钱)
【发布时间】:2013-10-03 01:33:30
【问题描述】:

我有一些 OCaml 代码,可以找到给定变化量的所有变化组合。我的大部分代码都在工作,但是我无法弄清楚这个递归函数将如何实际返回可能的更改组合。

let change_combos presidents = 
  let rec change amount coinlist =  match amount with 
    |0 -> [[]] (*exits when nothing*)
    |_ when (amount < 0) -> [] (*exits when less than 0*)
    |_ -> match coinlist with
    |[] -> [] (*Returns empty list, exits program*)

(*h::f -> something, using [25;10;5;1] aka all change combinations...*)
(*using recursion, going through all combinations and joining lists returned together*)

let print_the_coin_matrix_for_all_our_joy enter_the_matrix =
print_endline (join "\n" (List.map array_to_string enter_the_matrix));;

感谢您的帮助,如果我需要澄清一些事情,请告诉我:)

【问题讨论】:

  • 这段代码太零碎了,不能多说。我认为您要问的一般答案是函数由表达式(具有值的东西)定义。该值是函数返回的值。但这可能没有帮助 :-) 也许你可以问一些更具体的问题。
  • 所以我认为我应该能够像这样进行连接: let join concat all_my_lists = List.fold_left (fun x y -> x ^ concat ^ y) "" all_my_lists;; let array_to_string array = join ", " (List.map string_of_int array);;但不确定如何实际调用递归函数来返回“更改”的所有组合......希望这让它更清楚一点。
  • 一点建议,当您嵌套match … with 构造时,使用括号。

标签: optimization recursion functional-programming ocaml


【解决方案1】:

您要查找的内容有点令人困惑。我相信你想生成一个列表的所有组合的列表?您应该考虑递归以及如何生成单个元素。从输入类型开始,以及如何通过减少问题空间来生成连续元素。

let rec generate lst = match lst with
  | []   -> []
  | h::t -> [h] :: (List.map (fun x -> h::x) (generate t)) @ (generate t)

如果列表是[],则没有组合。如果我们有一个元素,我们会生成没有该元素的所有组合,并将我们的构造基于该假设。此时组件就位。将t 的组合列表与th cons'd 的组合连接到每个和h 的单例上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 2020-07-26
    • 2023-03-24
    • 2019-06-04
    相关资源
    最近更新 更多