Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 37s
Kahn's algorithm BFS topological sort:
let topo_sort n adj =
let in_deg = Array.make n 0 in
for i = 0 to n - 1 do
List.iter (fun j -> in_deg.(j) <- in_deg.(j) + 1) adj.(i)
done;
let q = Queue.create () in
for i = 0 to n - 1 do
if in_deg.(i) = 0 then Queue.push i q
done;
let count = ref 0 in
while not (Queue.is_empty q) do
let u = Queue.pop q in
count := !count + 1;
List.iter (fun v ->
in_deg.(v) <- in_deg.(v) - 1;
if in_deg.(v) = 0 then Queue.push v q
) adj.(u)
done;
!count
Graph: 0->{1,2}; 1->{3}; 2->{3,4}; 3->{5}; 4->{5}; 5.
Acyclic, so all 6 nodes can be ordered.
Tests Queue.{create,push,pop,is_empty}, mutable array via closure.
144 baseline programs total.
33 lines
595 B
OCaml
33 lines
595 B
OCaml
let topo_sort n adj =
|
|
let in_deg = Array.make n 0 in
|
|
for i = 0 to n - 1 do
|
|
List.iter (fun j -> in_deg.(j) <- in_deg.(j) + 1) adj.(i)
|
|
done;
|
|
let q = Queue.create () in
|
|
for i = 0 to n - 1 do
|
|
if in_deg.(i) = 0 then Queue.push i q
|
|
done;
|
|
let count = ref 0 in
|
|
while not (Queue.is_empty q) do
|
|
let u = Queue.pop q in
|
|
count := !count + 1;
|
|
List.iter (fun v ->
|
|
in_deg.(v) <- in_deg.(v) - 1;
|
|
if in_deg.(v) = 0 then Queue.push v q
|
|
) adj.(u)
|
|
done;
|
|
!count
|
|
|
|
;;
|
|
|
|
let n = 6 in
|
|
let adj = [|
|
|
[1; 2];
|
|
[3];
|
|
[3; 4];
|
|
[5];
|
|
[5];
|
|
[]
|
|
|] in
|
|
topo_sort n adj
|