Skip to content

Commit

Permalink
feat(p19): add lazy collection implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
pmpknu committed Oct 29, 2024
1 parent 54e4114 commit 5957e14
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion p12/lib/dune
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
(library
(name p12_lib)
(modules iterative map module rec tailrec))
(modules iterative map module rec tailrec lazy))
24 changes: 24 additions & 0 deletions p12/lib/lazy.ml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
let triangular_numbers =
Seq.unfold
(fun n ->
let t = n * (n + 1) / 2 in
Some (t, n + 1))
1
;;

let count_factors_tail n =
let rec aux i count =
if i * i > n
then count
else if n mod i = 0
then aux (i + 1) (count + if i * i = n then 1 else 2)
else aux (i + 1) count
in
if n <= 0 then 0 else aux 1 0
;;

let find_first_triangular_with_factors n =
Seq.find (fun x -> count_factors_tail x > n) triangular_numbers
;;

let result = find_first_triangular_with_factors 500
8 changes: 8 additions & 0 deletions p12/test/test_p12.ml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,13 @@ let test_map_find_first _ =
| None -> assert_failure "Expected a result, got None"
;;

(* Lazy collections tests *)
let test_lazy_find_first _ =
match Map.result with
| Some x -> assert_equal 76576500 x
| None -> assert_failure "Expected a result, got None"
;;

let suite =
"Project Euler Problem 12 Tests"
>::: [ "Tailrec - count_factors" >:: test_tailrec_count_factors
Expand All @@ -61,6 +68,7 @@ let suite =
; "Iterative - find_triangular" >:: test_iterative_find_triangle
; "Module - result" >:: test_module_result
; "Map - result" >:: test_map_find_first
; "Lazy - result" >:: test_lazy_find_first
]
;;

Expand Down

0 comments on commit 5957e14

Please sign in to comment.