examples graphs; small program that computes the collatz suite

This commit is contained in:
Simon Cruanes 2013-03-21 12:25:03 +01:00
parent e0b6b8be5b
commit 9cd07d3395
4 changed files with 55 additions and 2 deletions

View file

@ -4,6 +4,7 @@ IMPLEMENTATION_FILES = $(shell find -name '*.ml')
TARGETS_LIB = containers.cmxa containers.cma TARGETS_LIB = containers.cmxa containers.cma
TARGET_THREAD_LIB = thread_containers.cmxa thread_containers.cma TARGET_THREAD_LIB = thread_containers.cmxa thread_containers.cma
EXAMPLES = examples/mem_size.native examples/collatz.native
OPTIONS = -use-ocamlfind OPTIONS = -use-ocamlfind
all: lib lib_thread all: lib lib_thread
@ -14,8 +15,8 @@ lib:
lib_thread: lib_thread:
ocamlbuild $(OPTIONS) $(TARGETS_LIB) $(TARGET_THREAD_LIB) ocamlbuild $(OPTIONS) $(TARGETS_LIB) $(TARGET_THREAD_LIB)
examples: examples: all
ocamlbuild $(OPTIONS) -I . examples/mem_size.native ocamlbuild $(OPTIONS) -I . $(EXAMPLES)
tests: tests:
ocamlbuild $(OPTIONS) -package oUnit -I . tests/run_tests.native ocamlbuild $(OPTIONS) -package oUnit -I . tests/run_tests.native

20
examples/collatz.ml Normal file
View file

@ -0,0 +1,20 @@
(** Display the graph of the collatz conjecture, starting from the given int *)
let g = LazyGraph.map
~edges:(fun () -> [])
~vertices:(fun i -> [`Label (string_of_int i)])
LazyGraph.collatz_graph
let collatz n filename =
Format.printf "print graph to %s@." filename;
let out = open_out filename in
let fmt = Format.formatter_of_out_channel out in
LazyGraph.Dot.pp ~name:"collatz" g fmt (Enum.singleton n);
Format.pp_print_flush fmt ();
close_out out
let _ =
if Array.length Sys.argv < 3
then (Format.printf "use: collatz num file@."; exit 0)
else collatz (int_of_string Sys.argv.(1)) Sys.argv.(2)

View file

@ -390,3 +390,29 @@ module Dot = struct
let enum = Full.bfs_full graph vertices in let enum = Full.bfs_full graph vertices in
pp_enum ~eq:graph.eq ~hash:graph.hash ~name formatter enum pp_enum ~eq:graph.eq ~hash:graph.hash ~name formatter enum
end end
(** {2 Example of graphs} *)
let divisors_graph =
let rec divisors acc j i =
if j = i then acc
else
let acc' = if (i mod j = 0) then j :: acc else acc in
divisors acc' (j+1) i
in
let force i =
if i > 2
then
let l = divisors [] 2 i in
let edges = Enum.map (fun i -> (), i) (Enum.of_list l) in
Node (i, i, edges)
else
Node (i, i, Enum.empty)
in make force
let collatz_graph =
let force i =
if i mod 2 = 0
then Node (i, i, Enum.singleton ((), i / 2))
else Node (i, i, Enum.singleton ((), i * 3 + 1))
in make force

View file

@ -207,3 +207,9 @@ module Dot : sig
(** Pretty print the given graph (starting from the given set of vertices) (** Pretty print the given graph (starting from the given set of vertices)
to the channel in DOT format *) to the channel in DOT format *)
end end
(** {2 Example of graphs} *)
val divisors_graph : (int, int, unit) t
val collatz_graph : (int, int, unit) t