Topological sort: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(Add Tailspin solution)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(23 intermediate revisions by 7 users not shown)
Line 56:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V data = [
‘des_system_lib’ = Set(‘std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee’.split(‘ ’)),
‘dw01’ = Set(‘ieee dw01 dware gtech’.split(‘ ’)),
Line 104:
R r
 
print(toposort2(&data).join("\n"))</langsyntaxhighlight>
 
{{out}}
Line 120:
The specification:
 
<langsyntaxhighlight Adalang="ada">with Ada.Containers.Vectors; use Ada.Containers;
 
package Digraphs is
Line 171:
type Graph_Type is new Conn_Vec.Vector with null record;
 
end Digraphs;</langsyntaxhighlight>
 
The implementation:
 
<langsyntaxhighlight Adalang="ada">package body Digraphs is
 
function Node_Count(Graph: Graph_Type) return Node_Idx_With_Null is
Line 280:
end Top_Sort;
 
end Digraphs;</langsyntaxhighlight>
 
'''Set_of_Names: Translating strings into numbers and vice versa'''
Line 286:
The specification:
 
<langsyntaxhighlight Adalang="ada">private with Ada.Containers.Indefinite_Vectors;
 
generic
Line 327:
type Set is new Vecs.Vector with null record;
 
end Set_Of_Names;</langsyntaxhighlight>
 
The implementation
 
<langsyntaxhighlight Adalang="ada">package body Set_Of_Names is
 
use type Ada.Containers.Count_Type, Vecs.Cursor;
Line 398:
end Name;
 
end Set_Of_Names;</langsyntaxhighlight>
 
'''Toposort: Putting things together for the main program'''
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Digraphs, Set_Of_Names, Ada.Command_Line;
 
procedure Toposort is
Line 484:
TIO.Put_Line("There is no topological sorting -- the Graph is cyclic!");
end;
end Toposort;</langsyntaxhighlight>
 
{{out}}
Line 494:
 
<pre>There is no topological sorting -- the Graph is cyclic!</pre>
 
=={{header|ATS}}==
 
For ATS2 (patsopt/patscc) and a garbage collector (Boehm GC). The algorithm used is depth-first search.
 
You can compile this program with something like
"patscc -o topo -DATS_MEMALLOC_GCBDW topo.dats -lgc"
 
(Or you can use the libc malloc and just let the memory leak: "patscc -o topo -DATS_MEMALLOC_LIBC topo.dats")
 
<syntaxhighlight lang="ATS">
(*------------------------------------------------------------------*)
(* The Rosetta Code topological sort task. *)
(*------------------------------------------------------------------*)
 
#include "share/atspre_staload.hats"
staload UN = "prelude/SATS/unsafe.sats"
 
(* Macros for list construction. *)
#define NIL list_nil ()
#define :: list_cons
 
(*------------------------------------------------------------------*)
(* A shorthand for list reversal. This could also have been written as
a macro. *)
 
fn {a : t@ype}
rev {n : int}
(lst : list (INV(a), n))
:<!wrt> list (a, n) =
(* The list_reverse template function returns a linear list. Convert
that result to a "regular" list. *)
list_vt2t (list_reverse<a> lst)
 
(*------------------------------------------------------------------*)
(* Some shorthands for string operations. These are written as
macros. *)
 
macdef substr (s, i, n) =
(* string_make_substring returns a linear strnptr, but we want a
"regular" string. *)
strnptr2string (string_make_substring (,(s), ,(i), ,(n)))
 
macdef copystr (s) =
(* string0 copy returns a linear strptr, but we want a "regular"
string. *)
strptr2string (string0_copy (,(s)))
 
(*------------------------------------------------------------------*)
 
local
 
(* A boolean type for setting marks, and a vector of those. *)
typedef _mark_t = [b : nat | b <= 1] uint8 b
typedef _marksvec_t (n : int) = arrayref (_mark_t, n)
 
(* Some type casts that seem not to be implemented in the
prelude. *)
implement g1int2uint<intknd, uint8knd> i = $UN.cast i
implement g1uint2int<uint8knd, intknd> i = $UN.cast i
 
in
 
abstype marks (n : int)
assume marks n = _marksvec_t n
 
fn marks_make_elt
{n : nat}
{b : int | b == 0 || b == 1}
(n : size_t n,
b : int b)
:<!wrt> _marksvec_t n =
arrayref_make_elt (n, g1i2u b)
 
fn
marks_set_at
{n : int}
{i : nat | i < n}
{b : int | b == 0 || b == 1}
(vec : _marksvec_t n,
i : size_t i,
b : int b)
:<!refwrt> void =
vec[i] := g1i2u b
 
fn
marks_get_at
{n : int}
{i : nat | i < n}
(vec : _marksvec_t n,
i : size_t i)
:<!ref> [b : int | b == 0 || b == 1]
int b =
g1u2i vec[i]
 
fn
marks_setall
{n : int}
{b : int | b == 0 || b == 1}
(vec : _marksvec_t n,
n : size_t n,
b : int b)
:<!refwrt> void =
let
prval () = lemma_arrayref_param vec
var i : [i : nat | i <= n] size_t i
in
for* {i : nat | i <= n}
.<n - i>.
(i : size_t i) =>
(i := i2sz 0; i <> n; i := succ i)
vec[i] := g1i2u b
end
 
overload [] with marks_set_at of 100
overload [] with marks_get_at of 100
overload setall with marks_setall of 100
 
end
 
(*------------------------------------------------------------------*)
(* Reading dependencies from a file. The format is kept very simple,
because this is not a task about parsing. (Though I have written
an S-expression parser in ATS, and there is JSON support in the
ATS contributions package.) *)
 
(* The format of a dependencies description. The second and later
entries of each sublist forms the list of dependencies of the first
entry. Thus this is a kind of association list. *)
typedef depdesc (n : int) = list (List1 String1, n)
typedef depdesc = [n : nat] depdesc n
 
typedef char_skipper =
{n : int}
{i : nat | i <= n}
(string n,
size_t n,
size_t i) -<cloref> (* A closure. *)
[j : int | i <= j; j <= n]
size_t j
 
fn
make_char_skipper
(match : char -<> bool)
:<> char_skipper =
let
fun
skipper {n : int}
{i : nat | i <= n}
.<n - i>.
(s : string n,
n : size_t n,
i : size_t i)
:<cloref> [j : int | i <= j; j <= n]
size_t j =
if i = n then
i
else if ~match s[i] then
i
else
skipper (s, n, succ i)
in
skipper (* Return a closure. *)
end
 
val skip_spaces = make_char_skipper (lam c => isspace c)
val skip_ident =
make_char_skipper (lam c => (~isspace c) * (c <> ';'))
 
fn is_end_of_list (c : char) :<> bool = (c = ';')
 
fn
read_row {n : int}
{i : nat | i <= n}
(text : string n,
n : size_t n,
i : size_t i)
:<!wrt> [j : int | i <= j; j <= n]
@(List0 String1, size_t j) =
let
fun
loop {i : nat | i <= n}
.<n - i>.
(row : List0 String1,
i : size_t i)
:<!wrt> [j : int | i <= j; j <= n]
@(List0 String1, size_t j) =
let
val i = skip_spaces (text, n, i)
in
if i = n then
@(rev row, i)
else if is_end_of_list text[i] then
@(rev row, succ i)
else
let
val j = skip_ident (text, n, i)
val () = $effmask_exn assertloc (i < j)
val nodename = substr (text, i, j - i)
in
loop (nodename :: row, j)
end
end
in
loop (NIL, i)
end
 
fn
read_desc {n : int}
{i : nat | i <= n}
(text : string n,
n : size_t n,
i : size_t i)
:<!wrt> [j : int | i <= j; j <= n]
@(depdesc, size_t j) =
let
fun
loop {i : nat | i <= n}
.<n - i>.
(desc : depdesc,
i : size_t i)
:<!wrt> [j : int | i <= j; j <= n]
@(depdesc, size_t j) =
let
val i = skip_spaces (text, n, i)
in
if i = n then
@(rev desc, i)
else if is_end_of_list text[i] then
@(rev desc, succ i)
else
let
val @(row, j) = read_row (text, n, i)
val () = $effmask_exn assertloc (i < j)
in
if length row = 0 then
loop (desc, j)
else
loop (row :: desc, j)
end
end
in
loop (NIL, i)
end
 
fn
read_to_string ()
: String =
(* This simple implementation reads input only up to a certain
size. *)
let
#define BUFSIZE 8296
var buf = @[char][BUFSIZE] ('\0')
var c : int = $extfcall (int, "getchar")
var i : Size_t = i2sz 0
in
while ((0 <= c) * (i < pred (i2sz BUFSIZE)))
begin
buf[i] := int2char0 c;
i := succ i;
c := $extfcall (int, "getchar")
end;
copystr ($UN.cast{string} (addr@ buf))
end
 
fn
read_depdesc ()
: depdesc =
let
val text = read_to_string ()
prval () = lemma_string_param text
val n = strlen text
val @(desc, _) = read_desc (text, n, i2sz 0)
in
desc
end
 
(*------------------------------------------------------------------*)
(* Conversion of a dependencies description to the internal
representation for a topological sort. *)
 
(* An ordered list of the node names. *)
typedef nodenames (n : int) = list (String1, n)
 
(* A more efficient representation for nodes: integers in 0..n-1. *)
typedef nodenum (n : int) = [num : nat | num <= n - 1] size_t num
 
(* A collection of directed edges. Edges go from the nodenum that is
represented by the array index, to each of the nodenums listed in
the corresponding array entry. *)
typedef edges (n : int) = arrayref (List0 (nodenum n), n)
 
(* An internal representation of data for a topological sort. *)
typedef topodata (n : int) =
'{
n = size_t n, (* The number of nodes. *)
edges = edges n, (* Directed edges. *)
tempmarks = marks n, (* Temporary marks. *)
permmarks = marks n (* Permanent marks. *)
}
 
fn
collect_nodenames
(desc : depdesc)
:<!wrt> [n : nat]
@(nodenames n,
size_t n) =
let
fun
collect_row
{m : nat}
{n0 : nat}
.<m>.
(row : list (String1, m),
names : &nodenames n0 >> nodenames n1,
n : &size_t n0 >> size_t n1)
:<!wrt> #[n1 : int | n0 <= n1]
void =
case+ row of
| NIL => ()
| head :: tail =>
let
implement list_find$pred<String1> s = (s = head)
in
case+ list_find_opt<String1> names of
| ~ None_vt () =>
begin
names := head :: names;
n := succ n;
collect_row (tail, names, n)
end
| ~ Some_vt _ => collect_row (tail, names, n)
end
 
fun
collect {m : nat}
{n0 : nat}
.<m>.
(desc : list (List1 String1, m),
names : &nodenames n0 >> nodenames n1,
n : &size_t n0 >> size_t n1)
:<!wrt> #[n1 : int | n0 <= n1]
void =
case+ desc of
| NIL => ()
| head :: tail =>
begin
collect_row (head, names, n);
collect (tail, names, n)
end
 
var names : List0 String1 = NIL
var n : Size_t = i2sz 0
in
collect (desc, names, n);
@(rev names, n)
end
 
fn
nodename_number
{n : int}
(nodenames : nodenames n,
name : String1)
:<> Option (nodenum n) =
let
fun
loop {i : nat | i <= n}
.<n - i>.
(names : nodenames (n - i),
i : size_t i)
:<> Option (nodenum n) =
case+ names of
| NIL => None ()
| head :: tail =>
if head = name then
Some i
else
loop (tail, succ i)
 
prval () = lemma_list_param nodenames
in
loop (nodenames, i2sz 0)
end
 
fn
add_edge {n : int}
(edges : edges n,
from : nodenum n,
to : nodenum n)
:<!refwrt> void =
(* This implementation does not store duplicate edges. *)
let
val old_edges = edges[from]
implement list_find$pred<nodenum n> s = (s = to)
in
case+ list_find_opt<nodenum n> old_edges of
| ~ None_vt () => edges[from] := to :: old_edges
| ~ Some_vt _ => ()
end
 
fn
fill_edges
{n : int}
{m : int}
(edges : edges n,
n : size_t n,
desc : depdesc m,
nodenames : nodenames n)
:<!refwrt> void =
let
prval () = lemma_list_param desc
prval () = lemma_list_param nodenames
 
fn
clear_edges ()
:<!refwrt> void =
let
var i : [i : nat | i <= n] size_t i
in
for* {i : nat | i <= n}
.<n - i>.
(i : size_t i) =>
(i := i2sz 0; i <> n; i := succ i)
edges[i] := NIL
end
 
fun
fill_from_desc_entry
{m1 : nat}
.<m1>.
(headnum : nodenum n,
lst : list (String1, m1))
:<!refwrt> void =
case+ lst of
| NIL => ()
| name :: tail =>
let
val- Some num = nodename_number (nodenames, name)
in
if num <> headnum then
add_edge {n} (edges, num, headnum);
fill_from_desc_entry (headnum, tail)
end
 
fun
fill_from_desc
{m2 : nat}
.<m2>.
(lst : list (List1 String1, m2))
:<!refwrt> void =
case+ lst of
| NIL => ()
| list_entry :: tail =>
let
val+ headname :: desc_entry = list_entry
val- Some headnum = nodename_number (nodenames, headname)
in
fill_from_desc_entry (headnum, desc_entry);
fill_from_desc tail
end
in
clear_edges ();
fill_from_desc desc
end
 
fn
topodata_make
(desc : depdesc)
:<!refwrt> [n : nat]
@(topodata n,
nodenames n) =
let
val @(nodenames, n) = collect_nodenames desc
prval () = lemma_g1uint_param n
prval [n : int] EQINT () = eqint_make_guint n
 
val edges = arrayref_make_elt<List0 (nodenum n)> (n, NIL)
val () = fill_edges {n} (edges, n, desc, nodenames)
 
val tempmarks = marks_make_elt (n, 0)
and permmarks = marks_make_elt (n, 0)
 
val topo =
'{
n = n,
edges = edges,
tempmarks = tempmarks,
permmarks = permmarks
}
in
@(topo, nodenames)
end
 
(*------------------------------------------------------------------*)
(*
 
Topological sort by depth-first search. See
https://en.wikipedia.org/w/index.php?title=Topological_sorting&oldid=1092588874#Depth-first_search
 
*)
 
(* What return values are made from. *)
datatype toporesult (a : t@ype, n : int) =
| {0 <= n}
Topo_SUCCESS (a, n) of list (a, n)
| Topo_CYCLE (a, n) of List1 a
typedef toporesult (a : t@ype) = [n : int] toporesult (a, n)
 
fn
find_unmarked_node
{n : int}
(topo : topodata n)
:<!ref> Option (nodenum n) =
let
val n = topo.n
and permmarks = topo.permmarks
 
prval () = lemma_g1uint_param n
 
fun
loop {i : nat | i <= n}
.<n - i>.
(i : size_t i)
:<!ref> Option (nodenum n) =
if i = n then
None ()
else if permmarks[i] = 0 then
Some i
else
loop (succ i)
in
loop (i2sz 0)
end
 
fun
visit {n : int}
(topo : topodata n,
nodenum : nodenum n,
accum : List0 (nodenum n),
path : List0 (nodenum n))
: toporesult (nodenum n) =
(* Probably it is cumbersome to include a proof this routine
terminates. Thus I will not try to write one. *)
let
val n = topo.n
and edges = topo.edges
and tempmarks = topo.tempmarks
and permmarks = topo.permmarks
in
if permmarks[nodenum] = 1 then
Topo_SUCCESS accum
else if tempmarks[nodenum] = 1 then
let
val () = assertloc (isneqz path)
in
Topo_CYCLE path
end
else
let
fun
recursive_visits
{k : nat}
.<k>.
(topo : topodata n,
to_visit : list (nodenum n, k),
accum : List0 (nodenum n),
path : List0 (nodenum n))
: toporesult (nodenum n) =
case+ to_visit of
| NIL => Topo_SUCCESS accum
| node_to_visit :: tail =>
begin
case+ visit (topo, node_to_visit, accum, path) of
| Topo_SUCCESS accum1 =>
recursive_visits (topo, tail, accum1, path)
| other => other
end
in
tempmarks[nodenum] := 1;
case+ recursive_visits (topo, edges[nodenum], accum,
nodenum :: path) of
| Topo_SUCCESS accum1 =>
begin
tempmarks[nodenum] := 0;
permmarks[nodenum] := 1;
Topo_SUCCESS (nodenum :: accum1)
end
| other => other
end
end
 
fn
topological_sort
{n : int}
(topo : topodata n)
: toporesult (nodenum n, n) =
let
prval () = lemma_arrayref_param (topo.edges)
 
fun
sort (accum : List0 (nodenum n))
: toporesult (nodenum n, n) =
case+ find_unmarked_node topo of
| None () =>
let
prval () = lemma_list_param accum
val () = assertloc (i2sz (length accum) = topo.n)
in
Topo_SUCCESS accum
end
| Some nodenum =>
begin
case+ visit (topo, nodenum, accum, NIL) of
| Topo_SUCCESS accum1 => sort accum1
| Topo_CYCLE cycle => Topo_CYCLE cycle
end
 
val () = setall (topo.tempmarks, topo.n, 0)
and () = setall (topo.permmarks, topo.n, 0)
 
val accum = sort NIL
 
val () = setall (topo.tempmarks, topo.n, 0)
and () = setall (topo.permmarks, topo.n, 0)
in
accum
end
 
(*------------------------------------------------------------------*)
(* The function asked for in the task. *)
 
fn
find_a_valid_order
(desc : depdesc)
: toporesult String1 =
let
val @(topo, nodenames) = topodata_make desc
 
prval [n : int] EQINT () = eqint_make_guint (topo.n)
 
val nodenames_array =
arrayref_make_list<String1> (sz2i (topo.n), nodenames)
 
implement
list_map$fopr<nodenum n><String1> i =
nodenames_array[i]
 
(* A shorthand for mapping from nodenum to string. *)
macdef map (lst) =
list_vt2t (list_map<nodenum n><String1> ,(lst))
in
case+ topological_sort topo of
| Topo_SUCCESS valid_order => Topo_SUCCESS (map valid_order)
| Topo_CYCLE cycle => Topo_CYCLE (map cycle)
end
 
(*------------------------------------------------------------------*)
 
implement
main0 (argc, argv) =
let
val desc = read_depdesc ()
in
case+ find_a_valid_order desc of
| Topo_SUCCESS valid_order =>
println! (valid_order : List0 string)
| Topo_CYCLE cycle =>
let
val last = list_last cycle
val cycl = rev (last :: cycle)
in
println! ("COMPILATION CYCLE: ", cycl : List0 string)
end
end
 
(*------------------------------------------------------------------*)
</syntaxhighlight>
 
{{out}}
 
Data fed to standard input:
<pre>
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee;
dw01 ieee dw01 dware gtech;
dw02 ieee dw02 dware;
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech;
dw04 dw04 ieee dw01 dware gtech;
dw05 dw05 ieee dware;
dw06 dw06 ieee dware;
dw07 ieee dware;
dware ieee dware;
gtech ieee gtech;
ramlib std ieee;
std_cell_lib ieee std_cell_lib;
synopsys;
</pre>
 
Data from standard output:
<pre>
ieee, dware, dw05, dw06, dw07, gtech, dw01, dw04, dw02, std_cell_lib, synopsys, std, dw03, ramlib, des_system_lib
</pre>
 
AND ...
 
Data fed to standard input:
<pre>
a b; b d; d a e; e a;
</pre>
 
Data from standard output:
<pre>
COMPILATION CYCLE: a, e, d, b, a
</pre>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( ("des_system_lib".std synopsys "std_cell_lib" "des_system_lib" dw02 dw01 ramlib ieee)
(dw01.ieee dw01 dware gtech)
(dw02.ieee dw02 dware)
Line 544 ⟶ 1,257:
& out$("
compile order:" !indeps !res "\ncycles:" !cycles)
);</langsyntaxhighlight>
{{out}}
<pre>compile order:
Line 571 ⟶ 1,284:
=={{header|C}}==
Parses a multiline string and show the compile order. Note that four lines were added to the example input to form two separate cycles. Code is a little ugly.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 692 ⟶ 1,405:
 
return 0;
}</langsyntaxhighlight>
{{out}} (items on the same row can be compiled together)<syntaxhighlight lang="text">Compile order:
[unorderable] cycle_21 cycle_22
[unorderable] cycle_11 cycle_12
Line 699 ⟶ 1,412:
2: std_cell_lib ramlib dware gtech
3: dw02 dw01 dw05 dw06 dw07
4: des_system_lib dw03 dw04</langsyntaxhighlight>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">
namespace Algorithms
{
Line 843 ⟶ 1,556:
}
 
</syntaxhighlight>
</lang>
 
{{out}}<syntaxhighlight lang="text">B - depends on none
D - depends on none
G - depends on none
Line 854 ⟶ 1,567:
C - depends on D and E
A - depends on B and C
exiting...</langsyntaxhighlight>
{{out}}(with cycled dependency)<syntaxhighlight lang="text">Cycled dependencies detected: A C D
exiting...</langsyntaxhighlight>
 
=={{header|C++}}==
===C++11===
<langsyntaxhighlight lang="cpp">#include <map>
#include <set>
 
Line 996 ⟶ 1,709:
display_results(string(iterator(file), iterator()));
}
}</langsyntaxhighlight>
 
===C++17===
<langsyntaxhighlight lang="cpp">#include <unordered_map>
#include <unordered_set>
#include <vector>
Line 1,147 ⟶ 1,860:
 
return 0;
}</langsyntaxhighlight>
 
{{out}}<syntaxhighlight lang="text">I - depends on none
H - depends on none
G - depends on none
Line 1,167 ⟶ 1,880:
G - destroyed
H - destroyed
I - destroyed</langsyntaxhighlight>
{{out}}(with cycled dependency)<syntaxhighlight lang="text">Cycled dependencies detected: A D C
exiting...
A - destroyed
Line 1,178 ⟶ 1,891:
G - destroyed
H - destroyed
I - destroyed</langsyntaxhighlight>
 
=={{header|Clojure}}==
Line 1,192 ⟶ 1,905:
 
=====Implementation=====
<langsyntaxhighlight lang="clojure">(use 'clojure.set)
(use 'clojure.contrib.seq-utils)
 
Line 1,264 ⟶ 1,977:
[items]
(topo-sort-deps (deps items)))
</syntaxhighlight>
</lang>
 
Examples of sortable and non-sortable data:
 
<langsyntaxhighlight lang="clojure">(def good-sample
'(:des_system_lib (:std :synopsys :std_cell_lib :des_system_lib :dw02 :dw01 :ramlib :ieee)
:dw01 (:ieee :dw01 :dware :gtech)
Line 1,287 ⟶ 2,000:
 
(def bad-sample
(concat cyclic-dependence good-sample))</langsyntaxhighlight>
 
====={{out}}=====
<langsyntaxhighlight lang="clojure">Clojure 1.1.0
1:1 user=> #<Namespace topo>
1:2 topo=> (topo-sort good-sample)
(:std :synopsys :ieee :gtech :ramlib :dware :std_cell_lib :dw07 :dw06 :dw05 :dw01 :dw02 :des_system_lib :dw03 :dw04)
1:3 topo=> (topo-sort bad-sample)
"ERROR: cycles remain among (:dw01 :dw04 :dw03 :des_system_lib)"</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
toposort = (targets) ->
# targets is hash of sets, where keys are parent nodes and
Line 1,395 ⟶ 2,108:
console.log toposort targets
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun topological-sort (graph &key (test 'eql))
"Graph is an association list whose keys are objects and whose
values are lists of objects on which the corresponding key depends.
Line 1,445 ⟶ 2,158:
all-sorted-p
(unless all-sorted-p
entries)))))))</langsyntaxhighlight>
 
Provided example in which all items can be sorted:
 
<langsyntaxhighlight lang="lisp">> (defparameter *dependency-graph*
'((des-system-lib std synopsys std-cell-lib des-system-lib dw02 dw01 ramlib ieee)
(dw01 ieee dw01 dware gtech)
Line 1,468 ⟶ 2,181:
(IEEE DWARE DW02 DW05 DW06 DW07 GTECH DW01 DW04 STD-CELL-LIB SYNOPSYS STD DW03 RAMLIB DES-SYSTEM-LIB)
T
NIL</langsyntaxhighlight>
 
Provided example with <code>dw04</code> added to the dependencies of <code>dw01</code>. Some vertices are ordered, but the second return is <code>nil</code>, indicating that not all vertices could be sorted. The third return value is the hash table containing entries for the four vertices that couldn't be sorted. (The variable <code>[http://www.lispworks.com/documentation/HyperSpec/Body/v_sl_sls.htm /]</code> stores the list of values produced by the last form, and <code>[http://www.lispworks.com/documentation/HyperSpec/Body/f_descri.htm describe]</code> prints information about an object.)
 
<langsyntaxhighlight lang="lisp">> (defparameter *dependency-graph*
'((des-system-lib std synopsys std-cell-lib des-system-lib dw02 dw01 ramlib ieee)
(dw01 ieee dw01 dw04 dware gtech)
Line 1,499 ⟶ 2,212:
DW04 (1 DW01)
DW03 (1)
DES-SYSTEM-LIB (1)</langsyntaxhighlight>
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="crystal">def dfs_topo_visit(n, g, tmp, permanent, l)
if permanent.includes?(n)
return
Line 1,576 ⟶ 2,289:
puts ""
puts dfs_topo_sort(build_graph(data + circular_deps)).join(" -> ")
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,587 ⟶ 2,300:
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.algorithm, std.range;
 
final class ArgumentException : Exception {
Line 1,660 ⟶ 2,373:
foreach (const subOrder; depw.topoSort) // Should throw.
subOrder.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>#1 : ["ieee", "std", "synopsys"]
Line 1,674 ⟶ 2,387:
=={{header|E}}==
 
<langsyntaxhighlight lang="e">def makeQueue := <elib:vat.makeQueue>
 
def topoSort(data :Map[any, Set[any]]) {
Line 1,722 ⟶ 2,435:
return result
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">pragma.enable("accumulator")
 
def dataText := "\
Line 1,744 ⟶ 2,457:
def data := accum [].asMap() for rx`(@item.{17})(@deps.*)` in dataText.split("\n") { _.with(item.trim(), deps.split(" ").asSet()) }
 
println(topoSort(data))</langsyntaxhighlight>
 
{{out}}
Line 1,754 ⟶ 2,467:
''' Data
 
<langsyntaxhighlight lang="lisp">
(define dependencies
'((des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee)
Line 1,781 ⟶ 2,494:
(define (add-dependencies g dep-list)
(for* ((dep dep-list) (b (rest dep))) (a->b g b (first dep))))
</syntaxhighlight>
</lang>
'''Implementation
 
Remove all vertices with in-degree = 0, until to one left. (in-degree = number of arrows to a vertex)
<langsyntaxhighlight lang="lisp">
;; topological sort
;;
Line 1,818 ⟶ 2,531:
(error " ♻️ t-sort:cyclic" (map vertex-label (graph-cycle g))))))
 
</syntaxhighlight>
</lang>
{{Out}}
<langsyntaxhighlight lang="lisp">
(define g (make-graph "VHDL"))
(add-dependencies g dependencies)
Line 1,834 ⟶ 2,547:
t-sort (std synopsys ieee dware dw02 dw05 dw06 dw07 gtech ramlib std_cell_lib)
⛔️ error: ♻️ t-sort:cyclic (dw04 dw01)
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Topological do
def sort(library) do
g = :digraph.new
Line 1,883 ⟶ 2,596:
IO.puts ""
bad_libraries = Keyword.update!(libraries, :dw01, &[:dw04 | &1])
Topological.sort(bad_libraries)</langsyntaxhighlight>
 
{{out}}
Line 1,895 ⟶ 2,608:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
-module(topological_sort).
-compile(export_all).
Line 1,967 ⟶ 2,680:
digraph:add_vertex(G,D), % noop if dependency already added
digraph:add_edge(G,D,L). % Dependencies represented as an edge D -> L
</syntaxhighlight>
</lang>
 
{{out}}
<langsyntaxhighlight lang="erlang">
62> topological_sort:main().
synopsys -> std -> ieee -> dware -> dw02 -> dw05 -> ramlib -> std_cell_lib -> dw06 -> dw07 -> gtech -> dw01 -> des_system_lib -> dw03 -> dw04
Line 1,976 ⟶ 2,689:
dw04 -> dw01 -> dw04
dw01 -> dw04 -> dw01
ok</langsyntaxhighlight>
 
Erlang has a built in digraph library and datastructure. ''digraph_utils'' contains the ''top_sort'' function which provides a topological sort of the vertices or returns false if it's not possible (due to circular references).
Line 2,018 ⟶ 2,731:
 
{{works with|Gforth}}
<langsyntaxhighlight lang="forth">variable nodes 0 nodes ! \ linked list of nodes
 
: node. ( body -- )
Line 2,088 ⟶ 2,801:
deps dw01 ieee dw01 dware gtech dw04
 
all-nodes</langsyntaxhighlight>
 
{{out}}
Line 2,103 ⟶ 2,816:
This implementation is not optimal: for each ''level'' of dependency (for example A -> B -> C counts as three levels), there is a loop through all dependencies in IDEP.
It would be possible to optimize a bit, without changing the main idea, by first sorting IDEP according to first column, and using more temporary space, keeping track of where is located data in IDEP for each library (all dependencies of a same library being grouped).
<langsyntaxhighlight lang="fortran"> SUBROUTINE TSORT(NL,ND,IDEP,IORD,IPOS,NO)
IMPLICIT NONE
INTEGER NL,ND,NO,IDEP(ND,2),IORD(NL),IPOS(NL),I,J,K,IL,IR,IPL,IPR
Line 2,126 ⟶ 2,839:
IF(K.GT.J) GO TO 20
NO=J-1
END</langsyntaxhighlight>
 
An example. Dependencies are encoded to make program shorter (in array ICODE).
 
<langsyntaxhighlight lang="fortran"> PROGRAM EX_TSORT
IMPLICIT NONE
INTEGER NL,ND,NC,NO,IDEP,IORD,IPOS,ICODE,I,J,IL,IR
Line 2,167 ⟶ 2,880:
DO 50 I=NO+1,NL
50 PRINT*,LABEL(IORD(I))
END</langsyntaxhighlight>
 
{{out}}
Line 2,212 ⟶ 2,925:
===Modern Fortran===
A modern Fortran (95-2008) version of the TSORT subroutine is shown here (note that the IPOS array is not an input).
<langsyntaxhighlight lang="fortran">subroutine tsort(nl,nd,idep,iord,no)
 
implicit none
Line 2,249 ⟶ 2,962:
 
end subroutine tsort
</syntaxhighlight>
</lang>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">def topsort( graph ) =
val L = seq()
val S = seq()
Line 2,312 ⟶ 3,025:
case topsort( graph ) of
None -> println( 'un-orderable' )
Some( ordering ) -> println( ordering )</langsyntaxhighlight>
 
{{out}}
Line 2,322 ⟶ 3,035:
=={{header|Go}}==
===Kahn===
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,461 ⟶ 3,174:
}
return L, nil
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,473 ⟶ 3,186:
Topological sort only, this function can replace topSortKahn in above program. The
in-degree list is not needed.
<langsyntaxhighlight lang="go">// General purpose topological sort, not specific to the application of
// library dependencies. Also adapted from Wikipedia pseudo code.
func topSortDFS(g graph) (order, cyclic []string) {
Line 2,520 ⟶ 3,233:
}
return L, nil
}</langsyntaxhighlight>
{{out}}
(when used in program of Kahn example.)
Line 2,532 ⟶ 3,245:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List ((\\), elemIndex, intersect, nub)
import Data.Bifunctor (bimap, first)
 
Line 2,575 ⟶ 3,288:
 
main :: IO ()
main = print $ toposort depLibs</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="haskell">*Main> toposort depLibs
["std","synopsys","ieee","std_cell_lib","dware","dw02","gtech","dw01","ramlib","des_system_lib","dw03","dw04","dw05","dw06","dw07"]
 
*Main> toposort $ (\(xs,(k,ks):ys) -> xs++ (k,ks++" dw04"):ys) $ splitAt 1 depLibs
*** Exception: Dependency cycle detected for libs [["dw01","dw04"]]</langsyntaxhighlight>
 
=={{header|Huginn}}==
<langsyntaxhighlight lang="huginn">import Algorithms as algo;
import Text as text;
 
Line 2,656 ⟶ 3,369:
dfs = DepthFirstSearch();
print( "{}\n".format( dfs.topological_sort( dg ) ) );
}</langsyntaxhighlight>
 
==Icon and Unicon==
Line 2,669 ⟶ 3,382:
elements have been built.
 
<langsyntaxhighlight lang="icon">record graph(nodes,arcs)
global ex_name, in_name
 
Line 2,783 ⟶ 3,496:
g.arcs ? while arc := move(2) do if arc[1] == f then t ++:= arc[2]
return t
end</langsyntaxhighlight>
 
{{out}}
Line 2,810 ⟶ 3,523:
in parallel once the elements in the preceding lines have been built.
 
<langsyntaxhighlight lang="icon">record graph(nodes,arcs)
 
procedure main()
Line 2,896 ⟶ 3,609:
while (af := @cp, at := @cp) do if af == f then insert(t, at)
return t
end</langsyntaxhighlight>
 
=={{header|J}}==
 
(see [[Talk:Topological_sort#J_implementation|talk page]] for some details about what happens here.)
<lang J>dependencySort=: monad define
 
<syntaxhighlight lang="j">dependencySort=: monad define
parsed=. <@;:;._2 y
names=. {.&>parsed
Line 2,907 ⟶ 3,622:
assert.-.1 e. (<0 1)|:depends
(-.&names ~.;parsed),names /: +/"1 depends
)</langsyntaxhighlight>
 
With the sample data set:
Line 2,929 ⟶ 3,644:
We would get:
 
<langsyntaxhighlight Jlang="j"> >dependencySort dependencies
std
ieee
Line 2,944 ⟶ 3,659:
dw04
dw03
des_system_lib</langsyntaxhighlight>
 
If we tried to also make dw01 depend on dw04, the sort would fail because of the circular dependency:
 
<langsyntaxhighlight Jlang="j"> dependencySort dependencies,'dw01 dw04',LF
|assertion failure: dependencySort
| -.1 e.(<0 1)|:depends</langsyntaxhighlight>
 
Here is an alternate implementation which uses a slightly different representation for the dependencies (instead of a boolean connection matrix to represent connections, we use a list of lists of indices to represent connections):
 
<langsyntaxhighlight Jlang="j">depSort=: monad define
parsed=. <@;:;._2 y
names=. {.&>parsed
Line 2,961 ⟶ 3,676:
assert.-.1 e. (i.@# e.S:0"0 ])depends
(-.&names ~.;parsed),names /: #@> depends
)</langsyntaxhighlight>
 
It's results are identical to the first implementation, but this might be more efficient in typical cases.
Line 2,967 ⟶ 3,682:
=={{header|Java}}==
{{works with|Java|7}}
<langsyntaxhighlight lang="java">import java.util.*;
 
public class TopologicalSort {
Line 3,043 ⟶ 3,758:
return false;
}
}</langsyntaxhighlight>
 
<pre>[std, ieee, dware, dw02, dw05, dw06, dw07, gtech, dw01, dw04, ramlib, std_cell_lib, synopsys, des_system_lib, dw03]</pre>
Line 3,051 ⟶ 3,766:
====ES6====
 
<langsyntaxhighlight JavaScriptlang="javascript">const libs =
`des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
Line 3,108 ⟶ 3,823:
 
console.log('Solution:', S);
</langsyntaxhighlight>
 
Output:
<syntaxhighlight lang="javascript">
<lang JavaScript>
Solution: [
'ieee',
Line 3,128 ⟶ 3,843:
'dw03',
'des_system_lib' ]
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Line 3,149 ⟶ 3,864:
 
To solve and print the solution to the given problem on a 1GHz machine takes about 5ms.
<langsyntaxhighlight lang="jq"># independent/0 emits an array of the dependencies that have no dependencies
# Input: an object representing a normalized dependency graph
def independent:
Line 3,199 ⟶ 3,914:
normalize | [[], .] | _tsort ;
 
tsort</langsyntaxhighlight>
Data:
<langsyntaxhighlight lang="json">{"des_system_lib": [ "std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"],
"dw01": [ "ieee", "dw01", "dware", "gtech"],
"dw02": [ "ieee", "dw02", "dware"],
Line 3,215 ⟶ 3,930:
"synopsys": []
}
</syntaxhighlight>
</lang>
{{Out}}
<syntaxhighlight lang="jq">
<lang jq>
$ jq -c -f tsort.jq tsort.json
["ieee","std","synopsys","dware","gtech","ramlib","std_cell_lib","dw01","dw02","des_system_lib","dw03","dw04","dw05","dw06","dw07"]
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
Line 3,226 ⟶ 3,941:
{{trans|Python}}
 
<langsyntaxhighlight lang="julia">function toposort(data::Dict{T,Set{T}}) where T
data = copy(data)
for (k, v) in data
Line 3,262 ⟶ 3,977:
)
 
println("# Topologically sorted:\n - ", join(toposort(data), "\n - "))</langsyntaxhighlight>
 
{{out}}
Line 3,284 ⟶ 3,999:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.1.51
 
val s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " +
Line 3,351 ⟶ 4,066:
println("Following the addition of dw04 to the dependencies of dw01:")
println(g2.topoSort())
}</langsyntaxhighlight>
 
{{out}}
Line 3,367 ⟶ 4,082:
This version follows python implementation and returns List of Lists which is useful for parallel execution for example
</pre>
<langsyntaxhighlight lang="scala">
val graph = mapOf(
"des_system_lib" to "std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee".split(" ").toSet(),
Line 3,420 ⟶ 4,135:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,432 ⟶ 4,147:
 
=={{header|M2000 Interpreter}}==
<langsyntaxhighlight M2000lang="m2000 Interpreterinterpreter">Module testthis {
\\ empty stack
Flush
Line 3,529 ⟶ 4,244:
}
testthis
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,541 ⟶ 4,256:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Work in Mathematica 8 or higher versions.
<langsyntaxhighlight lang="mathematica">TopologicalSort[
Graph[Flatten[# /. {l_, ld_} :>
Map[# -> l &,
Line 3,559 ⟶ 4,274:
{"ramlib", {"std", "ieee"}},
{"std_cell_lib", {"ieee", "std_cell_lib"}},
{"synopsys", {}}}</langsyntaxhighlight>
{{Out}}
<pre>{"ieee", "std_cell_lib", "gtech", "dware", "dw07", "dw06", "dw05", \
Line 3,567 ⟶ 4,282:
 
=={{header|Mercury}}==
<syntaxhighlight lang="mercury">
<lang Mercury>
:- module topological_sort.
 
Line 3,645 ⟶ 4,360:
print(CompileOrder,!IO).
 
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
 
<langsyntaxhighlight Nimlang="nim">import sequtils, strutils, sets, tables, sugar
 
type StringSet = HashSet[string]
Line 3,731 ⟶ 4,446:
for key in data.keys: echo key
except ValueError:
echo getCurrentExceptionMsg()</langsyntaxhighlight>
 
=={{header|Object Pascal}}==
Written for Free Pascal, but will probably work in Delphi if you change the required units.
<syntaxhighlight lang="pascal">
<lang Object Pascal>
program topologicalsortrosetta;
 
Line 4,148 ⟶ 4,863:
InputList.Free;
end.
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let dep_libs = [
("des_system_lib", ["std"; "synopsys"; "std_cell_lib"; "des_system_lib"; "dw02"; "dw01"; "ramlib"; "ieee"]);
("dw01", (*"dw04"::*)["ieee"; "dw01"; "dware"; "gtech"]);
Line 4,205 ⟶ 4,920:
print_string "result: \n ";
print_endline (String.concat ", " res);
;;</langsyntaxhighlight>
 
If dw04 is added to the set of dependencies of dw01 to make the data un-orderable (uncomment it), an exception is raised:
Line 4,211 ⟶ 4,926:
 
=={{header|OxygenBasic}}==
<syntaxhighlight lang="text">
'TOPOLOGICAL SORT
 
Line 4,428 ⟶ 5,143:
next
ret
</syntaxhighlight>
</lang>
 
 
=={{header|Oz}}==
Using constraint propagation and search:
<langsyntaxhighlight lang="oz">declare
Deps = unit(
des_system_lib: [std synopsys std_cell_lib des_system_lib
Line 4,518 ⟶ 5,233:
{System.showInfo "\nBONUS - grouped by parallelizable compile jobs:"}
{PrintSolution Sol}
end</langsyntaxhighlight>
 
Output:
Line 4,547 ⟶ 5,262:
 
=={{header|Pascal}}==
======Kahn's algorithm======
See [[Topological_sort#Object Pascal | Object Pascal]]
This solution uses Kahn's algorithm, requires FPC version at least 3.2.0.
 
<syntaxhighlight lang="pascal">
program ToposortTask;
{$mode delphi}
uses
SysUtils, Generics.Collections;
 
type
TAdjList = class
InList, // incoming arcs
OutList: THashSet<string>; // outcoming arcs
constructor Create;
destructor Destroy; override;
end;
 
TDigraph = class(TObjectDictionary<string, TAdjList>)
procedure AddNode(const s: string);
procedure AddArc(const s, t: string);
function AdjList(const s: string): TAdjList;
{ returns True and the sorted sequence of nodes in aOutSeq if is acyclic,
otherwise returns False and nil; uses Kahn's algorithm }
function TryToposort(out aOutSeq: TStringArray): Boolean;
end;
 
 
constructor TAdjList.Create;
begin
InList := THashSet<string>.Create;
OutList := THashSet<string>.Create;
end;
 
destructor TAdjList.Destroy;
begin
InList.Free;
OutList.Free;
inherited;
end;
 
procedure TDigraph.AddNode(const s: string);
begin
if not ContainsKey(s) then
Add(s, TAdjList.Create);
end;
 
procedure TDigraph.AddArc(const s, t: string);
begin
AddNode(s);
AddNode(t);
if s <> t then begin
Items[s].OutList.Add(t);
Items[t].InList.Add(s);
end;
end;
 
function TDigraph.AdjList(const s: string): TAdjList;
begin
if not TryGetValue(s, Result) then
Result := nil;
end;
 
function TDigraph.TryToposort(out aOutSeq: TStringArray): Boolean;
var
q: TQueue<string>;
p: TPair<string, TAdjList>;
Node, ToRemove: string;
Counter: SizeInt;
begin
q := TQueue<string>.Create;
SetLength(aOutSeq, Count);
Counter := Pred(Count);
for p in Self do
if p.Value.InList.Count = 0 then
q.Enqueue(p.Key);
while q.Count > 0 do begin
ToRemove := q.Dequeue;
for Node in Items[ToRemove].OutList do
with Items[Node] do begin
InList.Remove(ToRemove);
if InList.Count = 0 then
q.Enqueue(Node);
end;
Remove(ToRemove);
aOutSeq[Counter] := ToRemove;
Dec(Counter);
end;
q.Free;
Result := Count = 0;
if not Result then
aOutSeq := nil;
end;
 
{ expects text separated by line breaks }
function ParseRawData(const aData: string): TDigraph;
var
Line, Curr, Node: string;
FirstTerm: Boolean;
begin
Result := TDigraph.Create([doOwnsValues]);
for Line in aData.Split([LineEnding], TStringSplitOptions.ExcludeEmpty) do begin
FirstTerm := True;
for Curr in Line.Split([' '], TStringSplitOptions.ExcludeEmpty) do
if FirstTerm then begin
Node := Curr;
Result.AddNode(Curr);
FirstTerm := False;
end else
Result.AddArc(Node, Curr);
end;
end;
 
procedure TrySort(const aData: string);
var
g: TDigraph;
Sorted: TStringArray;
begin
g := ParseRawData(aData);
if g.TryToposort(Sorted) then
WriteLn('success: ', LineEnding, string.Join(', ', Sorted))
else
WriteLn('circular dependency detected');
g.Free;
end;
 
const
ExampleData =
'des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee' + LineEnding +
'dw01 ieee dw01 dware gtech' + LineEnding +
'dw02 ieee dw02 dware' + LineEnding +
'dw03 std synopsys dware dw03 dw02 dw01 ieee gtech' + LineEnding +
'dw04 dw04 ieee dw01 dware gtech' + LineEnding +
'dw05 dw05 ieee dware' + LineEnding +
'dw06 dw06 ieee dware' + LineEnding +
'dw07 ieee dware' + LineEnding +
'dware ieee dware' + LineEnding +
'gtech ieee gtech' + LineEnding +
'ramlib std ieee' + LineEnding +
'std_cell_lib ieee std_cell_lib' + LineEnding +
'synopsys';
var
Temp: TStringArray;
 
begin
TrySort(ExampleData);
WriteLn;
//let's add a circular dependency
Temp := ExampleData.Split([LineEnding], TStringSplitOptions.ExcludeEmpty);
Temp[1] := Temp[1] + ' dw04';
TrySort(string.Join(LineEnding, Temp));
end.
</syntaxhighlight>
{{out}}
<pre>
success:
ieee, dware, gtech, std, dw01, dw02, synopsys, std_cell_lib, ramlib, dw04, dw05,
dw07, dw03, dw06, des_system_lib
 
circular dependency detected
</pre>
 
======Depth-first search======
 
Another solution uses DFS and can extract the found cycle; requires FPC version at least 3.2.0.
 
<syntaxhighlight lang="pascal">
program ToposortTask;
{$mode delphi}
uses
SysUtils, Generics.Collections;
 
type
TDigraph = class(TObjectDictionary<string, THashSet<string>>)
procedure AddNode(const s: string);
procedure AddArc(const s, t: string);
function AdjList(const s: string): THashSet<string>;
{ returns True and the sorted sequence of nodes in aOutSeq if is acyclic,
otherwise returns False and the first found cycle; uses DFS }
function TryToposort(out aOutSeq: TStringArray): Boolean;
end;
 
procedure TDigraph.AddNode(const s: string);
begin
if not ContainsKey(s) then
Add(s, THashSet<string>.Create);
end;
 
procedure TDigraph.AddArc(const s, t: string);
begin
AddNode(s);
AddNode(t);
if s <> t then
Items[s].Add(t);
end;
 
function TDigraph.AdjList(const s: string): THashSet<string>;
begin
if not TryGetValue(s, Result) then
Result := nil;
end;
 
function TDigraph.TryToposort(out aOutSeq: TStringArray): Boolean;
var
Parents: TDictionary<string, string>;// stores the traversal tree as pairs (Node, its predecessor)
procedure ExtractCycle(const BackPoint: string; Prev: string);
begin // just walk backwards through the traversal tree, starting from Prev until BackPoint is encountered
with TList<string>.Create do begin
Add(Prev);
repeat
Prev := Parents[Prev];
Add(Prev);
until Prev = BackPoint;
Add(Items[0]);
Reverse; //this is required since we moved backwards through the tree
aOutSeq := ToArray;
Free;
end
end;
var
Visited, // set of already visited nodes
Closed: THashSet<string>;// set of nodes whose subtree traversal is complete
Counter: SizeInt = 0;
function Dfs(const aNode: string): Boolean;// True means successful sorting,
var // False - found cycle
Next: string;
begin
Visited.Add(aNode);
for Next in AdjList(aNode) do
if not Visited.Contains(Next) then begin
Parents.Add(Next, aNode);
if not Dfs(Next) then exit(False);
end else
if not Closed.Contains(Next) then begin//back edge found(i.e. cycle)
ExtractCycle(Next, aNode);
exit(False);
end;
Closed.Add(aNode);
aOutSeq[Counter] := aNode;
Inc(Counter);
Result := True;
end;
var
Node: string;
begin
SetLength(aOutSeq, Count);
Visited := THashSet<string>.Create;
Closed := THashSet<string>.Create;
Parents := TDictionary<string, string>.Create;
Result := True;
for Node in Keys do
if not Visited.Contains(Node) then
if not Dfs(Node) then begin
Result := False;
break;
end;
Visited.Free;
Closed.Free;
Parents.Free;
end;
 
{ expects text separated by line breaks }
function ParseRawData(const aData: string): TDigraph;
var
Line, Curr, Node: string;
FirstTerm: Boolean;
begin
Result := TDigraph.Create([doOwnsValues]);
for Line in aData.Split([LineEnding], TStringSplitOptions.ExcludeEmpty) do begin
FirstTerm := True;
for Curr in Line.Split([' '], TStringSplitOptions.ExcludeEmpty) do
if FirstTerm then begin
Node := Curr;
Result.AddNode(Curr);
FirstTerm := False;
end else
Result.AddArc(Node, Curr);
end;
end;
 
procedure TrySort(const aData: string);
var
g: TDigraph;
Sorted: TStringArray;
begin
g := ParseRawData(aData);
if g.TryToposort(Sorted) then
WriteLn('success: ', LineEnding, string.Join(', ', Sorted))
else
WriteLn('circular dependency: ', LineEnding, string.Join('->', Sorted));
g.Free;
end;
 
const
ExampleData =
'des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee' + LineEnding +
'dw01 ieee dw01 dware gtech' + LineEnding +
'dw02 ieee dw02 dware' + LineEnding +
'dw03 std synopsys dware dw03 dw02 dw01 ieee gtech' + LineEnding +
'dw04 dw04 ieee dw01 dware gtech' + LineEnding +
'dw05 dw05 ieee dware' + LineEnding +
'dw06 dw06 ieee dware' + LineEnding +
'dw07 ieee dware' + LineEnding +
'dware ieee dware' + LineEnding +
'gtech ieee gtech' + LineEnding +
'ramlib std ieee' + LineEnding +
'std_cell_lib ieee std_cell_lib' + LineEnding +
'synopsys';
var
Temp: TStringArray;
 
begin
TrySort(ExampleData);
WriteLn;
//let's add a circular dependency
Temp := ExampleData.Split([LineEnding], TStringSplitOptions.ExcludeEmpty);
Temp[1] := Temp[1] + ' dw07';
Temp[7] := Temp[7] + ' dw03';
TrySort(string.Join(LineEnding, Temp));
end.
</syntaxhighlight>
{{out}}
<pre>
success:
ieee, dware, gtech, dw01, std, synopsys, dw02, ramlib, std_cell_lib, des_system_lib, dw06, dw03, dw07, dw05, dw04
 
circular dependency:
dw03->dw01->dw07->dw03
</pre>
 
=={{header|Perl}}==
Line 4,554 ⟶ 5,596:
The algorithm used allows the output to be clustered; libraries on the same line are all independent (given the building of any previous lines of libraries), and so could be built in parallel.
 
<langsyntaxhighlight lang="perl">sub print_topo_sort {
my %deps = @_;
 
Line 4,592 ⟶ 5,634:
print_topo_sort(%deps);
push @{ $deps{'dw01'} }, 'dw04'; # Add unresolvable dependency
print_topo_sort(%deps);</langsyntaxhighlight>
 
Output:<pre>ieee std synopsys
Line 4,606 ⟶ 5,648:
=={{header|Phix}}==
Implemented as a trivial normal sort.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">names</span>
<span style="color: #008080;">enum</span> <span style="color: #000000;">RANK</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">NAME</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">DEP</span> <span style="color: #000080;font-style:italic;">-- content of names
Line 4,697 ⟶ 5,739:
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nbad input:\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">topsort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">input</span><span style="color: #0000FF;">&</span><span style="color: #008000;">"\ndw01 dw04"</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
Items on the same line can be compiled at the same time, and each line is alphabetic.
Line 4,712 ⟶ 5,754:
dw02 dw05 dw06 dw07
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">topological_sort(Precedences, Sorted) =>
 
Edges = [K=V : [K,V] in Precedences],
Nodes = (domain(Edges) ++ range(Edges)).remove_dups(),
Sorted1 = [],
while (member(X,Nodes), not membchk(X,range(Edges)))
Sorted1 := Sorted1 ++ [X],
Nodes := Nodes.delete(X),
Edges := Edges.delete_key(X)
end,
% detect and remove a cycle
if Nodes.length > 0 then
println("\nThe graph is cyclic. Here's the detected cycle."),
println(nodes_in_cycle=Nodes),
println(edges_in_cycle=Edges),
Sorted = [without_cycle=Sorted1,cycle=Nodes]
else
Sorted = Sorted1
end,
nl.
 
% domain are the keys in L
domain(L) = [K : K=_V in L].
 
% range are the values of L
range(L) = [V : _K=V in L].
 
% deletes all pairs in L where a key is X
% (this is lessf on a multi-map in GNU SETL)
delete_key(L,X) = [K=V : K=V in L, K!=X].</syntaxhighlight>
 
The approach was inspired by a SETL snippet:
<pre>(while exists x in nodes | x notin range edges)
print(x);
nodes less:= x;
edges lessf:= x;
end;</pre>
 
Note: In contract to SETL, Picat doesn't support multi-maps, so this version uses a list of K=V (i.e. key=value).
 
===Test without cycles===
Identify and remove the cycles.
<syntaxhighlight lang="picat">main =>
deps(1,Deps),
Prec=[],
foreach(Lib=Dep in Deps)
Prec := Prec ++ [[D,Lib] : D in Dep, D != Lib]
end,
topological_sort(Prec,Sort),
println(Sort),
nl.
 
% Dependencies
deps(1,Deps) =>
Deps = [
des_system_lib=[std,synopsys,std_cell_lib,des_system_lib,dw02,dw01,ramlib,ieee],
dw01=[ieee,dw01,dware,gtech],
dw02=[ieee,dw02,dware],
dw03=[std,synopsys,dware,dw03,dw02,dw01,ieee,gtech],
dw04=[dw04,ieee,dw01,dware,gtech],
dw05=[dw05,ieee,dware],
dw06=[dw06,ieee,dware],
dw07=[ieee,dware],
dware=[ieee,dware],
gtech=[ieee,gtech],
ramlib=[std,ieee],
std_cell_lib=[ieee,std_cell_lib],
synopsys=[]
].</syntaxhighlight>
 
{{out}}
<pre>[std,synopsys,ieee,std_cell_lib,ramlib,dware,dw02,gtech,dw01,des_system_lib,dw03,dw04,dw05,dw06,dw07]</pre>
 
===Test with cycles===
<syntaxhighlight lang="picat">main =>
deps(with_cycle,Deps),
Prec=[],
foreach(Lib=Dep in Deps)
Prec := Prec ++ [[D,Lib] : D in Dep, D != Lib]
end,
topological_sort(Prec,Sort),
println(Sort),
nl.
 
deps(with_cycle,Deps) =>
Deps = [
des_system_lib=[std,synopsys,std_cell_lib,des_system_lib,dw02,dw01,ramlib,ieee],
% dw01=[ieee,dw01,dware,gtech], % orig
dw01=[ieee,dw01,dware,gtech,dw04], % make a cycle
dw02=[ieee,dw02,dware],
dw03=[std,synopsys,dware,dw03,dw02,dw01,ieee,gtech],
dw04=[dw04,ieee,dw01,dware,gtech],
dw05=[dw05,ieee,dware],
dw06=[dw06,ieee,dware],
dw07=[ieee,dware],
dware=[ieee,dware],
gtech=[ieee,gtech],
ramlib=[std,ieee],
std_cell_lib=[ieee,std_cell_lib],
synopsys=[],
% And some other cycles
cycle_1=[cycle_2],
cycle_2=[cycle_1],
cycle_3=[dw01,cycle_4,dw02,daw03],
cycle_4=[cycle_3,dw01,dw04]
].</syntaxhighlight>
 
{{out}}
<pre>The graph is cyclic. Here's the detected cycle.
nodes_in_cycle = [dw01,dw04,cycle_2,cycle_1,cycle_4,cycle_3,des_system_lib,dw03]
edges_in_cycle = [dw01 = des_system_lib,dw04 = dw01,dw01 = dw03,dw01 = dw04,cycle_2 = cycle_1,cycle_1 = cycle_2,dw01 = cycle_3,cycle_4 = cycle_3,cycle_3 = cycle_4,dw01 = cycle_4,dw04 = cycle_4]
 
[without_cycle = [std,synopsys,ieee,std_cell_lib,ramlib,dware,dw02,gtech,daw03,dw05,dw06,dw07],cycle = [dw01,dw04,cycle_2,cycle_1,cycle_4,cycle_3,des_system_lib,dw03]]</pre>
 
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de sortDependencies (Lst)
(setq Lst # Build a flat list
(uniq
Line 4,728 ⟶ 5,886:
(del (link @) 'Lst) # Yes: Store in result
(for This Lst # and remove from 'dep's
(=: dep (delete @ (: dep))) ) ) ) ) )</langsyntaxhighlight>
Output:
<pre>: (sortDependencies
Line 4,748 ⟶ 5,906:
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">#Input Data
$a=@"
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
Line 4,846 ⟶ 6,004:
"{0,-14} $($_."Library Dependencies")" -f $_.Library
}
}</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">#EndOfDataMarker$ = "::EndOfData::"
DataSection
;"LIBRARY: [LIBRARY_DEPENDENCY_1 LIBRARY_DEPENDENCY_2 ... LIBRARY_DEPENDENCY_N]
Line 4,967 ⟶ 6,125:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()</langsyntaxhighlight>
Sample output for no dependencies:
<pre>Compile order:
Line 4,997 ⟶ 6,155:
 
===Python 3===
<langsyntaxhighlight lang="python">try:
from functools import reduce
except:
Line 5,032 ⟶ 6,190:
assert not data, "A cyclic dependency exists amongst %r" % data
 
print ('\n'.join( toposort2(data) ))</langsyntaxhighlight>
 
'''Ordered output'''<br>
Line 5,050 ⟶ 6,208:
 
===Python 3.9 graphlib===
<langsyntaxhighlight lang="python">from graphlib import TopologicalSorter
 
# LIBRARY mapped_to LIBRARY DEPENDENCIES
Line 5,073 ⟶ 6,231:
 
ts = TopologicalSorter(data)
print(tuple(ts.static_order()))</langsyntaxhighlight>
 
{{out}}
Line 5,081 ⟶ 6,239:
 
First make the list
<syntaxhighlight lang="r">
<lang R>
deps <- list(
"des_system_lib" = c("std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"),
Line 5,096 ⟶ 6,254:
"std_cell_lib" = c("ieee", "std_cell_lib"),
"synopsys" = c())
</syntaxhighlight>
</lang>
 
Topological sort function. It will throw an error if it cannot complete, printing the list of items which cannot be ordered.
If it succeeds, returns the list of items in topological order.
<syntaxhighlight lang="r">
<lang R>
tsort <- function(deps) {
nm <- names(deps)
Line 5,132 ⟶ 6,290:
s
}
</syntaxhighlight>
</lang>
 
On the given example :
<syntaxhighlight lang="r">
<lang R>
tsort(deps)
# [1] "std" "ieee" "dware" "gtech" "ramlib"
# [6] "std_cell_lib" "synopsys" "dw01" "dw02" "dw03"
#[11] "dw04" "dw05" "dw06" "dw07" "des_system_lib"
</syntaxhighlight>
</lang>
 
If dw01 depends on dw04 as well :
 
<syntaxhighlight lang="r">
<lang R>
Unorderable items :
des_system_lib
Line 5,150 ⟶ 6,308:
dw04
dw03
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 5,212 ⟶ 6,370:
 
(topo-sort (clean G))
</syntaxhighlight>
</lang>
Output:
<langsyntaxhighlight lang="racket">
'(synopsys ieee dware gtech std_cell_lib std ramlib dw07 dw06 dw05 dw01 dw04 dw02 dw03 des_system_lib)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 5,222 ⟶ 6,380:
{{trans|Perl}}
{{Works with|rakudo|2016.01}}
<syntaxhighlight lang="raku" perl6line>sub print_topo_sort ( %deps ) {
my %ba;
for %deps.kv -> $before, @afters {
Line 5,258 ⟶ 6,416:
print_topo_sort(%deps);
%deps<dw01> = <ieee dw01 dware gtech dw04>; # Add unresolvable dependency
print_topo_sort(%deps);</langsyntaxhighlight>
 
Output:<pre>ieee std synopsys
Line 5,278 ⟶ 6,436:
Some of the FORTRAN 77 statements were converted to &nbsp; '''do''' &nbsp; loops (or &nbsp; '''do''' &nbsp; structures), &nbsp; and
<br>some variables were &nbsp; [https://en.wikipedia.org/wiki/Camel_case <u>''camel capitalized]''</u>.
<langsyntaxhighlight lang="rexx">/*REXX pgm does a topological sort (orders such that no item precedes a dependent item).*/
iDep.= 0; iPos.= 0; iOrd.= 0 /*initialize some stemmed arrays to 0.*/
nL= 15; nd= 44; nc= 69 /* " " "parms" and indices.*/
Line 5,320 ⟶ 6,478:
end /*i*/
end /*until*/
nO= j-1; return</langsyntaxhighlight>
{{out|output}}
<pre>
Line 5,347 ⟶ 6,505:
=={{header|Ruby}}==
Uses the [http://www.ruby-doc.org/stdlib/libdoc/tsort/rdoc/classes/TSort.html TSort] module from the Ruby stdlib.
<langsyntaxhighlight lang="ruby">require 'tsort'
class Hash
include TSort
Line 5,384 ⟶ 6,542:
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys</langsyntaxhighlight>
{{out}}
<pre>
Line 5,393 ⟶ 6,551:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::boxed::Box;
use std::collections::{HashMap, HashSet};
 
Line 5,505 ⟶ 6,663:
}
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 5,532 ⟶ 6,690:
=={{header|Scheme}}==
{{trans|Python}}
<langsyntaxhighlight lang="scheme">
(import (chezscheme))
(import (srfi srfi-1))
Line 5,618 ⟶ 6,776:
(newline)
(write (topological-sort unsortable))
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func print_topo_sort (deps) {
var ba = Hash.new;
deps.each { |before, afters|
Line 5,663 ⟶ 6,821:
print_topo_sort(deps);
deps{:dw01}.append('dw04'); # Add unresolvable dependency
print_topo_sort(deps);</langsyntaxhighlight>
{{out}}
<pre>
Line 5,681 ⟶ 6,839:
{{trans|Rust}}
 
<langsyntaxhighlight lang="swift">let libs = [
("des_system_lib", ["std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"]),
("dw01", ["ieee", "dw01", "dware", "gtech"]),
Line 5,749 ⟶ 6,907:
}
 
print(topologicalSort(libs: buildLibraries(libs))!)</langsyntaxhighlight>
 
{{out}}
Line 5,756 ⟶ 6,914:
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
data node <'.+'>, from <node>, to <node>
 
Line 5,779 ⟶ 6,937:
composer depRecord
(<WS>? def node: <~WS>; <WS>? <dep>* <WS>? $node -> ..|@collectDeps.v: {node: $};)
rule dep: (<~WS> -> ..|@collectDeps.e: {from: node´$node, to: node´$}; <WS>?)
end depRecord
$(3..last)... -> !depRecord
Line 5,801 ⟶ 6,959:
synopsys
' -> lines -> collectDeps -> topologicalSort -> !OUT::write
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,810 ⟶ 6,968:
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
proc topsort {data} {
# Clean the data
Line 5,846 ⟶ 7,004:
}
}
}</langsyntaxhighlight>
Demonstration code (which parses it from the format that the puzzle was posed in):
<langsyntaxhighlight lang="tcl">set inputData {
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
Line 5,867 ⟶ 7,025:
dict set parsedData [lindex $line 0] [lrange $line 1 end]
}
puts [topsort $parsedData]</langsyntaxhighlight>
Sample output:
<pre>ieee std synopsys dware gtech ramlib std_cell_lib dw01 dw02 dw05 dw06 dw07 des_system_lib dw03 dw04</pre>
Line 5,879 ⟶ 7,037:
 
{{works with|Bourne Shell}}
<langsyntaxhighlight lang="bash">$ awk '{ for (i = 1; i <= NF; i++) print $i, $1 }' <<! | tsort
> des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
> dw01 ieee dw01 dware gtech
Line 5,908 ⟶ 7,066:
dw03
ramlib
des_system_lib</langsyntaxhighlight>
 
If the graph of dependencies contains a cycle, [[BSD]]'s tsort(1) will print messages to standard error, break the cycle (by deleting one of the dependencies), continue the sort, and exit 0. So if dw04 becomes a dependency of dw01, then tsort(1) finds the cycle between dw01 and dw04.
Line 5,937 ⟶ 7,095:
unorderable libraries, if any, on the right. Self-dependences are
ignored and unlisted libraries are presumed independent.
<langsyntaxhighlight Ursalalang="ursala">tsort = ~&nmnNCjA*imSLs2nSjiNCSPT; @NiX ^=lxPrnSPX ^(~&rlPlT,~&rnPrmPljA*D@r)^|/~& ~&m!=rnSPlX</langsyntaxhighlight>
test program:
<langsyntaxhighlight Ursalalang="ursala">#import std
dependence_table = -[
Line 5,963 ⟶ 7,121:
#show+
 
main = <.~&l,@r ~&i&& 'unorderable: '--> mat` ~~ tsort parse dependence_table</langsyntaxhighlight>
With the given table, the output is
<pre>
Line 5,976 ⟶ 7,134:
=={{header|VBScript}}==
=====Implementation=====
<syntaxhighlight lang="vb">
<lang vb>
class topological
dim dictDependencies
Line 6,056 ⟶ 7,214:
end property
end class
</syntaxhighlight>
</lang>
 
=====Invocation=====
<syntaxhighlight lang="vb">
<lang vb>
dim toposort
set toposort = new topological
Line 6,083 ⟶ 7,241:
toposort.reset
next
</syntaxhighlight>
</lang>
 
=====Output=====
Line 6,166 ⟶ 7,324:
=={{header|Visual Basic .NET}}==
Adapted from http://tawani.blogspot.com/2009/02/topological-sorting-and-cyclic.html which was itself an adaptation of Java code. I added the Rosetta code specific format of dependencies, as well as checks for references to self.
<langsyntaxhighlight lang="vbnet">' Adapted from:
' http://tawani.blogspot.com/2009/02/topological-sorting-and-cyclic.html
' added/changed:
Line 6,495 ⟶ 7,653:
#End Region
End Class
</syntaxhighlight>
</lang>
=====Output=====
<pre>
Line 6,579 ⟶ 7,737:
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight ecmascriptlang="wren">class Graph {
construct new(s, edges) {
_vertices = s.split(", ")
Line 6,644 ⟶ 7,802:
var g2 = Graph.new(s, deps)
System.print("Following the addition of dw04 to the dependencies of dw01:")
System.print(g2.topoSort())</langsyntaxhighlight>
 
{{out}}
Line 6,658 ⟶ 7,816:
{{trans|Wikipedia}}
Input data is munged
<langsyntaxhighlight lang="zkl">fcn topoSort(data){ // data is L( L(root,L(leaves)),...)
allDs:=data.pump(List,fcn(rds){ T(Void.Write,Void.Write,rds[1]) }).copy();
roots:=Dictionary(data); // dictionary of root:leaves
Line 6,672 ⟶ 7,830:
if(roots) throw(Exception.ValueError("Cycle: "+roots.keys));
L
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">data:=T(
"des_system_lib", "std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee",
"dw01", "ieee dw01 dware gtech",
Line 6,691 ⟶ 7,849:
T( r, ds.replace(r,"").strip().split().copy() ) // leaves writable 'cause they will be
});
topoSort(data).println();</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits