Last active
August 27, 2025 05:49
-
-
Save jake-87/55d04a43ea42ca71eaabcfbb79d566d4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| let rand = | |
| let x = ref 10 in | |
| fun () -> | |
| x := (!x * 27527 + 27791) mod 41231; | |
| !x | |
| type tree = | |
| | Leaf | |
| | Branch of int * tree * tree | |
| let rec make_tree max depth = | |
| if depth <= 1 then Leaf | |
| else | |
| let r = rand () mod max in | |
| Branch(r, make_tree max (depth - 1), make_tree max (depth - 1)) | |
| let rec is_sub t k = | |
| match t, k with | |
| | Leaf, _ -> true | |
| | Branch(x,a,b), Branch(y,q,w) -> | |
| if x = y && is_sub a q && is_sub b w then true | |
| else | |
| is_sub t q || is_sub t w | |
| | _, _ -> false | |
| let bti = function | |
| | true -> 1 | |
| | false -> 0 | |
| let rec count_subtrees a t = | |
| match a with | |
| | Leaf -> 1 | |
| | Branch(_, x, y) -> | |
| bti (is_sub a t) + count_subtrees x t + count_subtrees y t | |
| let () = | |
| let t = make_tree 10 19 in | |
| let f = make_tree 9 19 in | |
| let time = Sys.time () in | |
| print_int (count_subtrees f t); | |
| Printf.printf "\nDONE: %fs\n" (Sys.time () -. time); | |
| flush stdout | |
| (* if you've implemented your version correctly it should output 512105 *) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
a C version for further comparison