Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2021
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1.  
  2. (** [lo -- hi] is the list containing the integers from [lo] to
  3. [hi], inclusive. For example, [0 -- 3] is [0; 1; 2; 3],
  4. and [4 -- 3] is [[]]. The implementation is tail recursive. *)
  5. let (--) lo hi =
  6. let rec loop lo hi acc =
  7. if lo > hi then acc
  8. else loop (lo + 1) hi (lo :: acc)
  9. in
  10. List.rev (loop lo hi [])
  11.  
  12.  
  13. let descCompare x y = if x<=y then 1 else -1;;
  14.  
  15.  
  16.  
  17.  
  18. let addValueToBag lst value = [value] @ lst;;
  19.  
  20. let rec sumOfBag l=
  21. match l with
  22. []->0
  23. | head::tail-> head + (sumOfBag tail);;
  24.  
  25.  
  26. let createBags bags n =
  27. let addBagToBags x = [] in
  28. List.init n addBagToBags
  29.  
  30.  
  31. let rec getSmallestBagSumIndex bags lowSum index smallestIndex =
  32. if index >= List.length bags then smallestIndex else
  33. let thisSum = sumOfBag (List.nth bags index) in
  34. if lowSum > thisSum then
  35. getSmallestBagSumIndex bags lowSum (index +1) index
  36. else
  37. getSmallestBagSumIndex bags lowSum (index +1) smallestIndex ;;
  38.  
  39.  
  40.  
  41.  
  42.  
  43. let partition lst =
  44. let bags = createBags [] 2 in (* create bag of bags *)
  45. let lst2 = List.sort descCompare lst in (* sort desc *)
  46. let smallestHelper baglst = getSmallestBagSumIndex baglst max_int 0 0 in
  47. (*create iterator helper *)
  48. let handleNextValue value =
  49. value ::(List.nth bags (smallestHelper bags)) in
  50. let matchBagsTo lst3 =
  51. match lst3 with
  52. | [] -> bags
  53. | h::t -> handleNextValue h and matchBagsTo t
  54.  
  55.  
  56.  
  57.  
  58.  
  59. let multi_partition n lst =
  60. failwith "Unimplemented";;
  61.  
  62.  
  63.  
  64. partition [4;5;6;7;8]
  65.  
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement