June 2018 Update
This commit is contained in:
parent
ba8067c3b7
commit
22f33d4004
5278 changed files with 84726 additions and 14379 deletions
139
Task/Topological-sort/C-sharp/topological-sort-1.cs
Normal file
139
Task/Topological-sort/C-sharp/topological-sort-1.cs
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
namespace Algorithms
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public class TopologicalSorter<ValueType>
|
||||
{
|
||||
private class Relations
|
||||
{
|
||||
public int Dependencies = 0;
|
||||
public HashSet<ValueType> Dependents = new HashSet<ValueType>();
|
||||
}
|
||||
|
||||
private Dictionary<ValueType, Relations> _map = new Dictionary<ValueType, Relations>();
|
||||
|
||||
public void Add(ValueType obj)
|
||||
{
|
||||
if (!_map.ContainsKey(obj)) _map.Add(obj, new Relations());
|
||||
}
|
||||
|
||||
public void Add(ValueType obj, ValueType dependency)
|
||||
{
|
||||
if (dependency.Equals(obj)) return;
|
||||
|
||||
if (!_map.ContainsKey(dependency)) _map.Add(dependency, new Relations());
|
||||
|
||||
var dependents = _map[dependency].Dependents;
|
||||
|
||||
if (!dependents.Contains(obj))
|
||||
{
|
||||
dependents.Add(obj);
|
||||
|
||||
if (!_map.ContainsKey(obj)) _map.Add(obj, new Relations());
|
||||
|
||||
++_map[obj].Dependencies;
|
||||
}
|
||||
}
|
||||
|
||||
public void Add(ValueType obj, IEnumerable<ValueType> dependencies)
|
||||
{
|
||||
foreach (var dependency in dependencies) Add(obj, dependency);
|
||||
}
|
||||
|
||||
public void Add(ValueType obj, params ValueType[] dependencies)
|
||||
{
|
||||
Add(obj, dependencies as IEnumerable<ValueType>);
|
||||
}
|
||||
|
||||
public Tuple<IEnumerable<ValueType>, IEnumerable<ValueType>> Sort()
|
||||
{
|
||||
List<ValueType> sorted = new List<ValueType>(), cycled = new List<ValueType>();
|
||||
var map = _map.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
|
||||
|
||||
sorted.AddRange(map.Where(kvp => kvp.Value.Dependencies == 0).Select(kvp => kvp.Key));
|
||||
|
||||
for (int idx = 0; idx < sorted.Count; ++idx) sorted.AddRange(map[sorted[idx]].Dependents.Where(k => --map[k].Dependencies == 0));
|
||||
|
||||
cycled.AddRange(map.Where(kvp => kvp.Value.Dependencies != 0).Select(kvp => kvp.Key));
|
||||
|
||||
return new Tuple<IEnumerable<ValueType>, IEnumerable<ValueType>>(sorted, cycled);
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_map.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
Example usage with Task object
|
||||
*/
|
||||
|
||||
namespace ExampleApplication
|
||||
{
|
||||
using Algorithms;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public class Task
|
||||
{
|
||||
public string Message;
|
||||
}
|
||||
|
||||
class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
List<Task> tasks = new List<Task>
|
||||
{
|
||||
new Task{ Message = "A - depends on B and C" }, //0
|
||||
new Task{ Message = "B - depends on none" }, //1
|
||||
new Task{ Message = "C - depends on D and E" }, //2
|
||||
new Task{ Message = "D - depends on none" }, //3
|
||||
new Task{ Message = "E - depends on F, G and H" }, //4
|
||||
new Task{ Message = "F - depends on I" }, //5
|
||||
new Task{ Message = "G - depends on none" }, //6
|
||||
new Task{ Message = "H - depends on none" }, //7
|
||||
new Task{ Message = "I - depends on none" }, //8
|
||||
};
|
||||
|
||||
TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();
|
||||
|
||||
// now setting relations between them as described above
|
||||
resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });
|
||||
//resolver.Add(tasks[1]); // no need for this since the task was already mentioned as a dependency
|
||||
resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });
|
||||
//resolver.Add(tasks[3]); // no need for this since the task was already mentioned as a dependency
|
||||
resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);
|
||||
resolver.Add(tasks[5], tasks[8]);
|
||||
//resolver.Add(tasks[6]); // no need for this since the task was already mentioned as a dependency
|
||||
//resolver.Add(tasks[7]); // no need for this since the task was already mentioned as a dependency
|
||||
|
||||
//resolver.Add(tasks[3], tasks[0]); // uncomment this line to test cycled dependency
|
||||
|
||||
var result = resolver.Sort();
|
||||
var sorted = result.Item1;
|
||||
var cycled = result.Item2;
|
||||
|
||||
if (!cycled.Any())
|
||||
{
|
||||
foreach (var d in sorted) Console.WriteLine(d.Message);
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.Write("Cycled dependencies detected: ");
|
||||
|
||||
foreach (var d in cycled) Console.Write($"{d.Message[0]} ");
|
||||
|
||||
Console.WriteLine();
|
||||
}
|
||||
|
||||
Console.WriteLine("exiting...");
|
||||
}
|
||||
}
|
||||
}
|
||||
10
Task/Topological-sort/C-sharp/topological-sort-2.cs
Normal file
10
Task/Topological-sort/C-sharp/topological-sort-2.cs
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
B - depends on none
|
||||
D - depends on none
|
||||
G - depends on none
|
||||
H - depends on none
|
||||
I - depends on none
|
||||
F - depends on I
|
||||
E - depends on F, G and H
|
||||
C - depends on D and E
|
||||
A - depends on B and C
|
||||
exiting...
|
||||
2
Task/Topological-sort/C-sharp/topological-sort-3.cs
Normal file
2
Task/Topological-sort/C-sharp/topological-sort-3.cs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
Cycled dependencies detected: A C D
|
||||
exiting...
|
||||
|
|
@ -30,7 +30,7 @@ string[][] topoSort(TDependencies d) pure /*nothrow @safe*/ {
|
|||
TDependencies dd;
|
||||
foreach (immutable item, const dep; d)
|
||||
if (!ordered.canFind(item))
|
||||
dd[item] = dep.filter!(s => !ordered.canFind(s)).array;
|
||||
dd[item] = dep.dup.filter!(s => !ordered.canFind(s)).array;
|
||||
d = dd;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ public class TopologicalSort {
|
|||
{8, 1}, {8, 10},
|
||||
{9, 1}, {9, 10},
|
||||
{10, 1},
|
||||
{11, 1}, {11, 10},
|
||||
{11, 1},
|
||||
{12, 0}, {12, 1},
|
||||
{13, 1}
|
||||
});
|
||||
|
|
|
|||
37
Task/Topological-sort/Julia/topological-sort.julia
Normal file
37
Task/Topological-sort/Julia/topological-sort.julia
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
function toposort(data::Dict{T,Set{T}}) where T
|
||||
data = copy(data)
|
||||
for (k, v) in data
|
||||
delete!(v, k)
|
||||
end
|
||||
extraitems = setdiff(reduce(∪, values(data)), keys(data))
|
||||
for item in extraitems
|
||||
data[item] = Set{T}()
|
||||
end
|
||||
rst = Vector{T}()
|
||||
while true
|
||||
ordered = Set(item for (item, dep) in data if isempty(dep))
|
||||
if isempty(ordered) break end
|
||||
append!(rst, ordered)
|
||||
data = Dict{T,Set{T}}(item => setdiff(dep, ordered) for (item, dep) in data if item ∉ ordered)
|
||||
end
|
||||
@assert isempty(data) "a cyclic dependency exists amongst $(keys(data))"
|
||||
return rst
|
||||
end
|
||||
|
||||
data = Dict{String,Set{String}}(
|
||||
"des_system_lib" => Set(split("std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee")),
|
||||
"dw01" => Set(split("ieee dw01 dware gtech")),
|
||||
"dw02" => Set(split("ieee dw02 dware")),
|
||||
"dw03" => Set(split("std synopsys dware dw03 dw02 dw01 ieee gtech")),
|
||||
"dw04" => Set(split("dw04 ieee dw01 dware gtech")),
|
||||
"dw05" => Set(split("dw05 ieee dware")),
|
||||
"dw06" => Set(split("dw06 ieee dware")),
|
||||
"dw07" => Set(split("ieee dware")),
|
||||
"dware" => Set(split("ieee dware")),
|
||||
"gtech" => Set(split("ieee gtech")),
|
||||
"ramlib" => Set(split("std ieee")),
|
||||
"std_cell_lib" => Set(split("ieee std_cell_lib")),
|
||||
"synopsys" => Set(),
|
||||
)
|
||||
|
||||
println("# Topologically sorted:\n - ", join(toposort(data), "\n - "))
|
||||
69
Task/Topological-sort/Kotlin/topological-sort.kotlin
Normal file
69
Task/Topological-sort/Kotlin/topological-sort.kotlin
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
// version 1.1.51
|
||||
|
||||
val s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " +
|
||||
"dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys"
|
||||
|
||||
val deps = mutableListOf(
|
||||
2 to 0, 2 to 14, 2 to 13, 2 to 4, 2 to 3, 2 to 12, 2 to 1,
|
||||
3 to 1, 3 to 10, 3 to 11,
|
||||
4 to 1, 4 to 10,
|
||||
5 to 0, 5 to 14, 5 to 10, 5 to 4, 5 to 3, 5 to 1, 5 to 11,
|
||||
6 to 1, 6 to 3, 6 to 10, 6 to 11,
|
||||
7 to 1, 7 to 10,
|
||||
8 to 1, 8 to 10,
|
||||
9 to 1, 9 to 10,
|
||||
10 to 1,
|
||||
11 to 1,
|
||||
12 to 0, 12 to 1,
|
||||
13 to 1
|
||||
)
|
||||
|
||||
class Graph(s: String, edges: List<Pair<Int,Int>>) {
|
||||
|
||||
val vertices = s.split(", ")
|
||||
val numVertices = vertices.size
|
||||
val adjacency = List(numVertices) { BooleanArray(numVertices) }
|
||||
|
||||
init {
|
||||
for (edge in edges) adjacency[edge.first][edge.second] = true
|
||||
}
|
||||
|
||||
fun hasDependency(r: Int, todo: List<Int>): Boolean {
|
||||
for (c in todo) if (adjacency[r][c]) return true
|
||||
return false
|
||||
}
|
||||
|
||||
fun topoSort(): List<String>? {
|
||||
val result = mutableListOf<String>()
|
||||
val todo = MutableList<Int>(numVertices) { it }
|
||||
try {
|
||||
outer@ while(!todo.isEmpty()) {
|
||||
for ((i, r) in todo.withIndex()) {
|
||||
if (!hasDependency(r, todo)) {
|
||||
todo.removeAt(i)
|
||||
result.add(vertices[r])
|
||||
continue@outer
|
||||
}
|
||||
}
|
||||
throw Exception("Graph has cycles")
|
||||
}
|
||||
}
|
||||
catch (e: Exception) {
|
||||
println(e)
|
||||
return null
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val g = Graph(s, deps)
|
||||
println("Topologically sorted order:")
|
||||
println(g.topoSort())
|
||||
println()
|
||||
// now insert 3 to 6 at index 10 of deps
|
||||
deps.add(10, 3 to 6)
|
||||
val g2 = Graph(s, deps)
|
||||
println("Following the addition of dw04 to the dependencies of dw01:")
|
||||
println(g2.topoSort())
|
||||
}
|
||||
|
|
@ -1,62 +1,46 @@
|
|||
/*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.*/
|
||||
label= 'DES_SYSTEM_LIB DW01 DW02 DW03 DW04 DW05 DW06 DW07 DWARE GTECH RAMLIB',
|
||||
'STD_CELL_LIB SYNOPSYS STD IEEE'
|
||||
|
||||
icode=1 14 13 12 1 3 2 11 15 0 2 15 2 9 10 0 3 15 3 9 0 4 14 213 9 4 3 2 15 10 0 5 5 15 2,
|
||||
iDep.=0; iPos.=0; iOrd.=0 /*initialize some stemmed arrays to 0.*/
|
||||
nL=15; nd=44; nc=69 /* " " "parms" and indices.*/
|
||||
label= 'DES_SYSTEM_LIB DW01 DW02 DW03 DW04 DW05 DW06 DW07 DWARE GTECH RAMLIB',
|
||||
'STD_CELL_LIB SYNOPSYS STD IEEE'
|
||||
iCode=1 14 13 12 1 3 2 11 15 0 2 15 2 9 10 0 3 15 3 9 0 4 14 213 9 4 3 2 15 10 0 5 5 15 2,
|
||||
9 10 0 6 6 15 9 0 7 7 15 9 0 8 15 9 0 39 15 9 0 10 15 10 0 11 14 15 0 12 15 12 0 0
|
||||
|
||||
idep.=0; ipos.=0; iord.=0 /*initialize some stemmed arrays to 0.*/
|
||||
nl=15; nd=44; nc=69; j=0; i=0 /* " " "parms" and indices.*/
|
||||
|
||||
10: i=i+1
|
||||
il=word(icode, i)
|
||||
if il==0 then signal 30
|
||||
20: i=i+1
|
||||
ir=word(icode, i)
|
||||
if ir==0 then signal 10
|
||||
j=j+1
|
||||
idep.j.1=il
|
||||
idep.j.2=ir
|
||||
signal 20
|
||||
30: call tsort
|
||||
say '═══compile order═══'
|
||||
q=0; do o=no by -1 for no; q=q+1
|
||||
say word(label, iord.o)
|
||||
end /*o*/
|
||||
if q==0 then q='no'
|
||||
say ' ('q "libraries found.)"
|
||||
say
|
||||
say '═══unordered libraries═══'
|
||||
q=0; do u=no+1 to nl; q=q+1
|
||||
say word(label, iord.u)
|
||||
end /*u*/
|
||||
if q==0 then q='no'
|
||||
say ' ('q "unordered libraries found.)"
|
||||
j=0
|
||||
do i=1
|
||||
iL=word(iCode, i); if iL==0 then leave
|
||||
do forever; i=i + 1
|
||||
iR=word(iCode, i); if iR==0 then leave
|
||||
j=j + 1
|
||||
iDep.j.1= iL
|
||||
iDep.j.2= iR
|
||||
end /*forever*/
|
||||
end /*i*/
|
||||
call tsort
|
||||
say '═══compile order═══'
|
||||
@= 'libraries found.)'
|
||||
#=0; do o=nO by -1 for nO; #= #+1; say word(label, iOrd.o)
|
||||
end /*o*/; if #==0 then #= 'no'
|
||||
say ' ('# @; say
|
||||
say '═══unordered libraries═══'
|
||||
#=0; do u=nO+1 to nL; #= #+1; say word(label, iOrd.u)
|
||||
end /*u*/; if #==0 then #= 'no'
|
||||
say ' ('# "unordered" @
|
||||
exit /*stick a fork in it, we're all done. */
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
tSort: procedure expose nl nd idep. iord. ipos. no
|
||||
do i=1 for nl
|
||||
iord.i=i
|
||||
ipos.i=i
|
||||
end /*i*/
|
||||
tSort: procedure expose iDep. iOrd. iPos. nd nL nO
|
||||
do i=1 for nL; iOrd.i=i; iPos.i=i
|
||||
end /*i*/
|
||||
k=1
|
||||
do forever
|
||||
j=k
|
||||
k=nl+1
|
||||
do i=1 for nd
|
||||
il=idep.i.1
|
||||
ir=ipos.il
|
||||
ipl=ipos.il
|
||||
ipr=ipos.ir
|
||||
if il==ir | ipl>.k | ipl<j | ipr<j then iterate
|
||||
k=k-1
|
||||
_=iord.k; ipos._=ipl
|
||||
ipos.il=k
|
||||
iord.ipl=iord.k
|
||||
iord.k=il
|
||||
end /*i*/
|
||||
if k<=j then leave
|
||||
end /*forever*/
|
||||
no=j-1
|
||||
return
|
||||
do until k<=j; j=k
|
||||
k=nL + 1
|
||||
do i=1 for nd
|
||||
iL =iDep.i.1 ; iR =iPos.iL
|
||||
ipL=iPos.iL ; ipR=iPos.iR
|
||||
if iL==iR | ipL>.k | ipL<j | ipR<j then iterate
|
||||
k=k - 1
|
||||
_=iOrd.k ; iPos._ =ipL
|
||||
iPos.iL=k
|
||||
iOrd.ipL=iOrd.k ; iOrd.k =iL
|
||||
end /*i*/
|
||||
end /*until*/
|
||||
nO=j - 1; return
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue