ocaml: phase 5.1 topo_sort.ml baseline (6-node DAG, all 6 ordered)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 37s
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.
This commit is contained in:
@@ -129,6 +129,7 @@
|
||||
"tail_factorial.ml": 479001600,
|
||||
"subset_sum.ml": 8,
|
||||
"tic_tac_toe.ml": 1,
|
||||
"topo_sort.ml": 6,
|
||||
"word_freq.ml": 8,
|
||||
"xor_cipher.ml": 601,
|
||||
"zerosafe.ml": 28,
|
||||
|
||||
32
lib/ocaml/baseline/topo_sort.ml
Normal file
32
lib/ocaml/baseline/topo_sort.ml
Normal file
@@ -0,0 +1,32 @@
|
||||
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
|
||||
Reference in New Issue
Block a user